Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Difference between using commas, concatenation, and string formatters in Python

I am learning python(2.7) on my own. I have learned that we can use the following ways to put strings and variables together in printing:

x = "Hello"
y = "World"

By using commas:

print "I am printing" , x, y  # I know that using comma gives automatic space

By using concatenation :

print "I am printing" + " " + x + " " + y 

By using string formatters

print "I am printing %s %s" % (x, y) 

In this case all three print the same:

I am printing Hello World

What is the difference between the three and are there any particular instances where one is preferred over the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.

As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.

There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.

1. Printing

In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.

Print Statements with Commas (Python 2)

The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.

You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.

For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):

x = "Hello"
y = "World"

print "I am printing",
print x,
print y 

Would output:

I am printing Hello World

Print Function

With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:

from __future__ import print_function

you can declare a separator and an end, which gives us a lot more flexibility:

>>> print('hello', 'world', sep='-', end='
****
')
hello-world
****
>>>

The defaults are ' ' for sep and ' ' for end:

>>> print('hello', 'world')
hello world
>>> 

2. String Concatenation

Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.

print('hello' + '-' + 'world')

will print

hello-world

Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.

print('here is a number: ' + str(2))

prints

here is a number: 2

If you attempt to concatenate the integer without coercing it to a string first:

>>> print('here is a number: ' + 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.

3. String Interpolation

The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).

The new way of doing that would be to do this (using the index of the arguments):

print('I am printing {0} and {1}'.format(x, y))

or in python 2.7 or 3 (using the implied index):

print('I am printing {} and {}'.format(x, y))

or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))

print('I am printing {x} and {y}'.format(x=x, y=y))

The biggest benefit of this over % style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments

print('I am printing {0} and {y}'.format(x, y=y))

New in Python 3.6, format literals

Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:

print(f'I am printing {x} and {y}')

The format literals can actually execute code in-place:

>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...