Converting numbers into string has many purposes such as formatting result in a data table, displaying big number, and combining number and string for displaying. Python provides str()
function for this task, which basically calls the __str__()
method of its parameter. The function will help users avoid encountering “TypeErrors” when converting int or float to a string when coding in Python.
Open any Python editors and follow these examples:
[python]
str(10234)
#output: ‘10234’
years = 5
print("I bought this car " + str(years) + " years ago.")
#output: ‘I bought this car 5 years ago.
result = ""
for i in range(1, 5):
result += str(i) + " "
print(result)
#output: 1 2 3 4 5
[/python]