When is str( ) useful?


#1

Question

When is str( ) useful?

Answer

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.


FAQ: Learn Python – Strings & Console Output – str()
#2

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!".


#3

i know how useful str() is, but some people who are new to programming will say we can simple do the following:

print "Hello! I have 6453 views on my YouTube video!"

could you explain why this is not always possible? If not, let me know, i will add an explanation. Thank you :slight_smile:


#4

Im a beginner and since there is no reply I would like to ask you that putting without str() is not possible sometimes because you would like something like a counter so you should put it like:

views = number_of_views (somehow that world like a view counter)
print “Hello! I have” + str(views) “views on my youtube video!”

if that is the case how you make a counter? Please message me back im avid to work in python.


#5

yea, for example youtube has a counter of how many times a video is watched, which comes from a database. Then str() is possible to join integer and string, but there are also other possibilities

a database might be a bit complex, and to increase views every time the page is visit, but a simplified version could be achieved with a loop:

for views in range(10):
   print “Hello! I have” + str(views) “views on my youtube video!”

#6

Thanks so much now I understand it better!
:grin: