Query with str()


Hey Everyone.

I realize that this has already been covered, but the replies given didn’t quit register with me so I apologize for repetition.

I just completed https://www.codecademy.com/courses/learn-python/lessons/strings--console-output/exercises/str but don’t want to hit next as I don’t feel I understand the concept properly.

The example states that using str() converts a variables non-string value into a string (seems simple enough).

If we use the example in the exercise;
pi = 3.14
print str(pi)
(Output = 3.14)

I fail to see what difference there is between just using;
pi = 3.14
print pi
(Output = 3.14)

Is this one of these accept the example as a given and it will make sense in time type scenarios?

I appreciate any help,


see what happens when you run:

print "the value of pi is: " + pi

and now try:

print "the value of pi is: " + str(pi)

see the difference? we can’t concatenate string and integer (pi), so we need to convert pi to string

this is just one practical example, of course there are many more situations where string conversion is useful, sometimes, codecademy teaches a concept, which pays off later


stetim94, thank you very much for the example. As soon as you mentioned concatenating a string which contains value that aren’t strings it sank in. (Although as you said I look forward to the thousands of other scenarios where this may serve a purpose).

In future I will accept what I can and realize that in time it will show it’s potential.

Thanks again :slight_smile:


sometimes the string conversion happens under the hood:

print "the value of pi is %d" % pi

or using format would be better:

print "the value of pi is {:d}".format(pi)

.format() is more robust and flexible, although we do not use str() here explicitly, converting to string happens

Knowing that conversion happens, and how to do it manually, is very useful.

Hope that my answer gave you enough insight.

is %s or %d already explained? %s is a string placeholder, %d is for a number (both integers and floats)



The first example makes perfect sense, I have just covered using %s to reference an existing variable, and you have made it easy to understand that %d is used in place of %s when dealing with a numerical value.
I don’t quite follow the format example but have a slight idea of what it represents, I’m sure I will cover it soon enough.

Thanks for all the help!

Edit: looking back at the second example, I think that {:d} is a place holder for the .format(pi) result. Correct?


you seem to understand fine

more then fine, yes {} is a placeholder for format, and :d tells format it can expect a number (just like d of %d

.format() is just more powerful and flexible, as you can read here:


in my personal opinion, i would prefer format

Hope that this helps


Most certainly does!!!

Thanks a bunch stetim94 :+1:


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