tostring() Equivalent in Python

The equivalent of the tostring() JavaScript function in Python is str().

 

The str() function takes any type of object and turns it into the data type of string, which is an iterable sequence of characters.

 

Demonstrate this, let's convert a variable with the data type of int to a string.

 

number = 12

string = str(number)

print(type(string))
print(string)
<class 'str'>
12

 

A key feature of the Python str() function is that it does not modify the original variable so you will need to store the result in another one.

 

f-strings

If you are seeking to format variables from various data types into a single string, use f-strings which were introduced in Python 3.

 

Open an f-string with f'' and inside it add variables inside {} (curly brackets). Here is an example of adding some numbers to a formatted string:

 

number = 12
number_2 = 24

output = f'First number is {number} and the second is {number_2}.'

print(output)
First number is 12 and the second is 24.