Kodeclik Blog
Python’s str() function
In Python, the integer 314 is different from the string “314”. The first can be used for calculations and the second can be used for string manipulation. To understand the difference you can use the type() function. Consider the following code:
num1 = 314
str1 = "314"
print(type(num1))
print(type(str1))
As expected, this will output:
<class 'int'>
<class 'str'>
reinforcing that num1 is an integer (of class “init”) and str1 is a string (of class “string”).
Python’s str() function allows you to take a non-string (e.g., num1 in the above example) and convert it into a string. Consider:
num1 = 314
str1 = "314"
print(type(num1))
print(type(str(num1)))
print(type(str1))
This outputs:
<class 'int'>
<class 'str'>
<class 'str'>
In the second line, note that we have used the str() function to convert num1 which was originally an integer into a string. Thus when we then apply type() on the resulting output, we obtain a string as expected.
To see what the conversion has done, we can do:
print(str(num1))
This will output:
314
You can use str() on a range of objects. Here are more examples:
pi = 3.14
gpa = 4.0
temperature = -15
print(pi, type(pi))
print(str(pi), type(str(pi)))
print()
print(gpa, type(gpa))
print(str(gpa), type(str(gpa)))
print()
print(temperature, type(temperature))
print(str(temperature), type(str(temperature)))
The output of this code will be:
3.14 <class 'float'>
3.14 <class 'str'>
4.0 <class 'float'>
4.0 <class 'str'>
-15 <class 'int'>
-15 <class 'str'>
Let us try lists:
mylist = ['Jan','Feb']
print(str(mylist))
The output is:
['Jan', 'Feb']
Similarly, if we try a dictionary:
mydict = {1: 'Jan',2: 'Feb'}
print(str(mydict))
we get:
{1: 'Jan', 2: 'Feb'}
As you can see for any given objects, str() essentially gives you a string representation of it that you can then use for other purposes (e.g., parsing, communication, etc.)
If you liked learning about the str() function, you will like our post on checking if a Python string is an integer and also how to
print any Python object as a string.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.