简体   繁体   中英

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM