search

How to check if a variable is a string in Python?

To check if a variable is a string in Python, you can use the isinstance() function or compare the type of the variable to the str type. Here's an example:

# Using isinstance()
x = "Hello"
if isinstance(x, str):
    print("x is a string")
else:
    print("x is not a string")

# Using type()
y = 10
if type(y) == str:
    print("y is a string")
else:
    print("y is not a string")

In the above example, the isinstance() function is used to check if the variable x is an instance of the str type. If it is, it prints "x is a string"; otherwise, it prints "x is not a string".

Similarly, the type() function is used to compare the type of the variable y with the str type. If they are equal, it prints "y is a string"; otherwise, it prints "y is not a string".

Note that the isinstance() function is more flexible when checking against multiple types, as it allows passing a tuple of types as the second argument.

Keep in mind that in Python, strings can be defined using single quotes ('), double quotes ("), or triple quotes (''' or """). The checks above will consider all valid string representations as strings.

Additionally, it's worth noting that in Python, strings are considered immutable objects.

Related Questions You Might Be Interested