Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
3 views
in Python by (3.4k points)
edited by

In Python 2.6, the str.format() has been introduced and has a slightly different syntax than existing % operator. When should I use which one and who's better?

  • I tried this and used each method and the outcome I received is same, then what's the difference between two of them?

#!/usr/bin/python
sub1 = "an Amimal!"
sub2 = "horn"

q = "It's me %s" % sub1
w = "It's me {0}".format(sub1)

e = "with big %(kwarg)s!" % {'kwarg':sub2}
r = "with big {kwarg}!".format(kwarg=sub2)

print q    # "It's me an animal!"
print w    # "It's me an animal!"
print e    # "with big horn!"
print r    # "with big horn!"

  •  I am also confused when string formatting occurs in Python? Is this happen when my logging level is set to High will I still have a problem while performing the following  operation? And if this is true than how can I avoid this?

 log.debug("some debug info: %s" % some_info)

closed

3 Answers

0 votes
by (46k points)
edited by
 
Best answer

% either takes a variable or a tuple whereas .format don't have these issues, for instance check this:

"hi there %s" % name

for your second doubt, I assume you're using logging module , then try this:

log.debug("some debug info: %s", some_info)

This will avoid all formatting unless your logger logs something.

+1 vote
by (10.9k points)
edited by

Example of % operator :

 "Hello %s" % text

But , The above code doesn’t always work. Suppose we text happens to be (1,1,1) then it will show a TypeEror, in such cases you need to modify the code a little:

"some debug info: %s" % (text,) 

.format doesn't have such problems so we prefer using it most of the time .As per your second question, string formatting happens when the string formatting expression is evaluated. In your example, "some debug info:" will be first evaluated and then passed to the log.debug().

0 votes
by (106k points)

You can use something that the modulo operator ( % ) can't do:

tu = (12,45,22222,103,6)

print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)

result

12 22222 45 22222 103 22222 6 22222

You can use the following video tutorials to clear all your doubts:-

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...