Converting numbers into strings has many purposes such as formatting results in a data table, displaying big numbers, and combining numbers and strings 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:
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