Differences between basic strings help

This is the place for queries that don't fit in any of the other categories.

Differences between basic strings help

Postby sc25893 » Mon May 20, 2013 7:50 pm

Hi everyone,

I am reading about strings and experimenting at the same time and could do with some explanation about the following:

Code: Select all
typeOfWeather = "snow"
temperature = "cold"

print "The %s outside is very %s!" %(typeOfWeather, temperature)
print "The " + str(typeOfWeather) + " outside is very " + str(temperature)  + "!"
print "The {0} outside is very {1}!".format(typeOfWeather, temperature)

As you can see, this lot just outputs the same line three times. I believe the first one is 'older' python and the last one is newer. I'm running v2.7 and all three of these run ok.

The middle one, obviously more hassle to write, but seems to do the same thing. I'm sure this is not the case and some reasoning behind which method would be deemed more suitable would be really helpful. Maybe this is a bad example but I appreciate any input. Thanks.
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Differences between basic strings help

Postby setrofim » Mon May 20, 2013 8:09 pm

In short, use the last method. The first is, as you rightly pointed out, an older version of the last. You will often see it being used in existing scripts, but its use in new code is discouraged in favor of the last method. The second method is string concatenation (whereas the other two are string formatting"). It is less convinient to type and to read (as you're breaking up the message), it is less flexible ( you can't specify formatting options such as the number of digits after a decimal point for floats), it may, depending on your system, be a bit slower (though in examples such as this, it really isn't that significant).
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: Differences between basic strings help

Postby Kebap » Mon May 20, 2013 11:26 pm

I sometimes use the second way when I am writing quick and dirty code. You can also reduce it more. As both "typeOfWeather" and "temperature" are already strings, you can drop the "str()":

Code: Select all
print "The " + typeOfWeather + " outside is very " + temperature  + "!"

For me, this is really easy to write. You have to make sure you get the spaces in the strings correct and it can get ugly quickly, so I can't encourage you to keep this for more complicated code. Then use the other method.
New Users, Read These Hints

Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Posts: 614
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], Hakalaken, micseydel and 17 guests