0

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.

2
  • 1
    The comma , operator implicitly adds a space in the output text but you can control this behaviour by using % operator. Commented Jan 4, 2015 at 5:17
  • I copy-pasted your codes and both outputs are same. Commented Jan 4, 2015 at 5:21

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.