Str()


#1

Please leave the following link in the post so we can find the unit module, else replace it with a link to the exact lesson:

Strings and Console Output

Hi, I’ve a question and I hope someone can reply to it.
the exercise explains that str() converts non-strings into strings, for example if I write <print “There” + “are” + 2 + “toys”> the console gets me an error so i have to write: <print “There” + “are” + str(2) + “toys”>; Now I’ve converted 2(=non-string) into a string and the console prints the phrase correctly, but I can also write the number 2 into two quotation marks and it’s more simple than the first one, right? or not?
thanks to help me!


#2

It would be difficult to wrap quotes around numbers derived from a math operation and would make our code look pretty strange. That is why we have a function like str to do the job for us.


#3

Technically str just asks the value for a string. str is a type just like list or int

But yeah, addition between str and int doesn’t really make sense. And yeah, "2" is a character like any other, no reason to treat it different from letters, spaces, etc. You also probably shouldn’t be splitting the string up like that, instead you’d do: 'There are 2 toys'


#4

You may also find Exercise 14: String Formatting with %, Part 1 and Exercise 15: String Formatting with %, Part 2 helpful regarding this topic. The same technique presented in those two exercises can be used to format numerical values for inclusion within strings.

Be aware that there are additional means of formatting output that are not presented in those exercises.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.