Often at times you’ll want to combine numbers with a string to display useful information on the screen. This is made possible by converting those numbers to strings so they can be printed together. If you wanted to get a user’s height in centimeters, for example, they’d enter a number as a string, that would need to be converted to a number to be used in a formula, and then converted back to a string using str( ) to be displayed in a sentence.
str() is very useful if you want to print numbers as strings. Say you wanted to combine some strings, and one of them was a number; you would have to use str() e.g print "Hello! I have " + str(6453) " views on my YouTube video!".
Again you need to stress that var= always results in a string …some languages have looked at the characters and assumed integer fr instance…Python insists on you being specific – confused my little brain
its not just about printing a string. String conversion can be useful at other times too.
i recently pulled an id (auto increment integer) from url and from database, these two id’s had to be compared, but the comparison was failing because of different data types (string and integer), so had to do a conversion. This is just one example, and i am sure there are many more
This lesson is about learning about data types and casting, sure, in this case you can get away with using , and let python handle the casting/conversion.
Actually it prints just fine, but not as a single string. The values are not concatenated but comma separated in the print() argument.
Numbers cannot be concatenated with strings.
>>> a = 6453
>>> print ("Hello! I have " + a + " views on my YouTube video!")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print ("Hello! I have " + a + " views on my YouTube video!")
TypeError: Can't convert 'int' object to str implicitly
The str() constructor comes to the rescue in this instance…
>>> print ("Hello! I have " + str(a) + " views on my YouTube video!")
Hello! I have 6453 views on my YouTube video!
There may be instances where such a statement is dynamic and string formatting is not convenient or workable for the progammer’s purposes. Having this function at our disposal addresses those situations.
As string formatting goes, Python coerces everything to string so we don’t have to re-cast values in the argument list. Witness the examples above.