Tuesday, March 2, 2021

Stack Abuse: Python: Check if Variable is a String

Introduction

Python is a dynamically typed language, and the variable data types are inferred without explicit intervention by the developer.

If we had code that requires a string to work correctly but lacked type hints, which are optional, how can we avoid errors if the variable used is not a string?

In this tutorial, we'll take a look at how to check if a variable is a string in Python, using the type() and isinstance() functions, as well as the is operator:

Developers usually use type() and is, though, these can be limited in certain contexts, in which case, it's better to use the isinstance() function.

Check if Variable is a String with type()

The built-in type() function can be used to return the data type of an object. For example, we'll be expecting the returned value of this function to be <class 'str'>.

Let's initialize a string variable, with a couple of other non-string variables and test this function out:

string = "'Do, or do not. There is no try.' - Yoda"
integer = 42
float = 3.14

# Print results
print("The type of string is ", type(string))
print("The type of integer is ", type(number))
print("The type of float is ", type(float))

Now, if we run this code, it'll result in:

"The type of string is  <class 'str'>"
"The type of integer is  <class 'int'>"
"The type of float is  <class 'float'>"

To apply this logic in a way we can alter the code-flow, we can compare the returned value of the type() function with the str class:

user_name = 35

# Checks if variable is a string
if (type(user_name)) == str:
    print("User's name is a string")
else:
    print("User's name is not a string")

This results in:

User's age is not a string

Check if Variable is a String with is Operator

Python's is operator is an identity operator, meaning it checks if two compared variables point to the same memory location.

Just as in the previous example, we've compared the result of the type() function with the str class, we can also use the is operator:

user_name = "John Doe"

# Checks if variable is a string
if (type(user_name)) is str:
    print("User's name is a string")
else:
    print("User's name is not a string")

This results in:

User's name is a string

Check if Variable is a String with isinstance()

Now, the most fail-safe approach is the isinstance() function. It accepts two arguments - the variable we're checking, and the type we're checking for.

In our case, it'll be a variable and the str class.

Let's create a couple of variables and check their types:

string = "Hello there!"
integer = 42

print("Is string a string?: ", isinstance(string, str))
print("Is integer a string?: ", isinstance(integer, str))

This results in:

"Is string a string?:  True"
"Is integer a string?:  False"

Conclusion

Python is a dynamically typed language, which introduces a lot of user-induced errors. In a lot of cases, we don't have any guarantee is a variable passed to a method is of the type we're expecting it to be in.

In this tutorial, we've covered three ways to check if a variable is a string in Python - using the type() and isinstance() functions, as well as the is operator.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...