Civic
Civic

Reputation: 3

Python 2.7: % string format vs. calling variable outside string?

I'm teaching myself Python and can't see a huge difference between these two examples except the extra formatting options (eg. %r) that string formatting provides.

name = "Bob"
print "Hi, my name is %s." % name
print "Hi, my name is", name

Is there any reason in general why you'd prefer one over the other? I realise that .format() is the preferred way to do this now, but this just for me to better understand how Python operates.

Upvotes: 0

Views: 376

Answers (3)

kindall
kindall

Reputation: 184260

The primary difference between the two (which no one else seems to be describing) is this:

print "Hi, my name is %s." % name

Here, a new string is being constructed from the two strings (the string literal and the value of name). Interpolation (the % operator) is an operation you could use anywhere—for example, in a variable assignment or a function call—not just in a print statement. This newly-minted string is then printed (then discarded, because it is not given a name).

print "Hi, my name is", name

Here, the two strings are simply printed one after the other with a space in between. The print statement is doing all the work. No string operations are performed and no new string is created.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799062

The difference is that the comma is part of the print statement, not of the string. Attempting to use it elsewhere, e.g. binding a string to a name, will not do what you want.

Upvotes: 1

It is programming choice:

1) Using % clarifies the type to the reader of the code, but for each additional variable used, the programmer will need to spend time in modifying in 2 places

2) Using , implicitly does % so the reader will have to look back to know about he type. But it is quick and if code is intuitively written removes a lot of burdon of maintenance

So yes, it is choice of maintaining balance between, maintenance, readability and convenience.

Upvotes: 1

Related Questions