In Python, to convert a variable to a string, you can use the str() function. There is no tostring() method like in other languages.

a = 3
a_as_str = str(a)

print(a, type(a))
print(a_as_str, type(a_as_str))

#Output:
3 
3 

When using various programming languages, the ability to be able to convert variables from one variable type to another is very valuable. Many programming languages have the method tostring() to be able to get a string representation of a variable.

Python does not have a tostring method to convert a variable to a string. Instead, Python has the str() function which will change an object into a string.

str() converts any object into a string. When we call str(), it calls the object’s __str__() function internally to get the representation of the object as a string.

Below are some examples in Python of converting various objects to a string variable with str().

a = 3
b = [1, 2, 3]
c = { "apple": 1, "banana": 2}

print(str(a), type(str(a)))
print(str(b), type(str(b)))
print(str(c), type(str(c))) 

#Output:
3 
[1, 2, 3] 
{'apple': 1, 'banana': 2} 

Using format() to Convert an Object into a String in Python

Another way you can convert a variable into a string is using format(). format() takes in variables and inputs them into strings.

Below are some examples of converting different variables to strings with format().

a = 3
b = [1, 2, 3]
c = { "apple": 1, "banana": 2}

print("{}".format(a), type("{}".format(a)))
print("{}".format(b), type("{}".format(b)))
print("{}".format(c), type("{}".format(c))) 

#Output:
3 
[1, 2, 3] 
{'apple': 1, 'banana': 2} 

Using f-strings to Convert Objects into String Using Python

Another way you can convert a variable into a string is using f-strings. f-strings take in variables and inputs them into strings.

Below are some examples of converting different variables to strings with f-strings in Python.

a = 3
b = [1, 2, 3]
c = { "apple": 1, "banana": 2}

print(f"{a}", type(f"{a}"))
print(f"{b}", type(f"{b}"))
print(f"{c}", type(f"{c}")) 

#Output:
3 
[1, 2, 3] 
{'apple': 1, 'banana': 2} 

Hopefully this article has been useful for you to learn that there is no tostring() method in Python, and how to convert an object to a string in Python with str().

Categorized in:

Python,

Last Update: February 26, 2024