Question

I've been looking around and I've been unable to find a definitive answer to this question: what's the recommended way to print variables in Python?

So far, I've seen three ways: using commas, using percent signs, or using plus signs:

>>> a = "hello"
>>> b = "world"
>>> print a, "to the", b
hello to the world
>>> print "%s to the %s" % (a, b)
hello to the world
>>> print a + " to the " + b
hello to the world

Each method seems to have its pros and cons.

Commas allow to write the variable directly and add spaces, as well as automatically perform a string conversion if needed. But I seem to remember that good coding practices say that it's best to separate your variables from your text.

Percent signs allow that, though they require to use a list when there's more than one variable, and you have to write the type of the variable (though it seems able to convert even if the variable type isn't the same, like trying to print a number with %s).

Plus signs seem to be the "worst" as they mix variables and text, and don't convert on the fly; though maybe it is necessary to have more control on your variable from time to time.

I've looked around and it seems some of those methods may be obsolete nowadays. Since they all seem to work and each have their pros and cons, I'm wondering: is there a recommended method, or do they all depend on the context?

Was it helpful?

Solution 2

string.format() basics

Here are a couple of example of basic string substitution, the {} is the placeholder for the substituted variables. If no format is specified, it will insert and format as a string.

s1 = "so much depends upon {}".format("a red wheel barrow")
s2 = "glazed with {} water beside the {} chickens".format("rain", "white")

You can also use the numeric position of the variables and change them in the strings, this gives some flexibility when doing the formatting, if you made a mistake in the order you can easily correct without shuffling all variables around.

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")

The format() function offers a fair amount of additional features and capabilities, here are a few useful tips and tricks using .format()

Named Arguments

You can use the new string format as a templating engine and use named arguments, instead of requiring a strict order.

madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table")
>>> I took the cheese off the table

Reuse Same Variable Multiple Times

Using the % formatter, requires a strict ordering of variables, the .format() method allows you to put them in any order as we saw above in the basics, but also allows for reuse.

str = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
>>> Oh Romeo, Romeo! wherefore art thou Romeo?

Use Format as a Function

You can use .format as a function which allows for some separation of text and formatting from code. For example at the beginning of your program you could include all your formats and then use later. This also could be a nice way to handle internationalization which not only requires different text but often requires different formats for numbers.

email_f = "Your email address was {email}".format
print(email_f(email="bob@example.com"))

Escaping Braces

If you need to use braces when using str.format(), just double up

print(" The {} set is often represented as {{0}} ".format("empty"))
>>> The empty set is often represented as {0}

OTHER TIPS

Including the values from identifiers inside a string is called string formatting. You can handle string formatting in different ways with various pros and cons.

  • Using string concatenation (+)
    • Con: You must manually convert objects to strings
    • Pro: The objects appear where you want to place the into the string
    • Con: The final layout may not be clear due to breaking the string literal
  • Using template strings (i.e. $bash-style substitution):
    • Pro: You may be familiar with shell variable expansion
    • Pro: Conversion to string is done automatically
    • Pro: Final layout is clear.
    • Con: You cannot specify how to perform the conversion
  • Using %-style formatting:
    • Pro: similar to formatting with C's printf.
    • Pro: conversions are done for you
    • Pro: you can specify different type of conversions, with some options (e.g. precision for floats)
    • Pro: The final layout is clear
    • Pro: You can also specify the name of the elements to substitute as in: %(name)s.
    • Con: You cannot customize handling of format specifiers.
    • Con: There are some corner cases that can puzzle you. To avoid them you should always use either tuple or dict as argument.
  • Using str.format:
    • All the pros of %-style formatting (except that it is not similar to printf)
    • Similar to .NET String.Format
    • Pro: You can manually specify numbered fields which allows you to use a positional argument multiple times
    • Pro: More options in the format specifiers
    • Pro: You can customize the formatting specifiers in custom types

The commas do not do string-formatting. They are part of the print statement statement syntax. They have a softspace "feature" which is gone in python3 since print is a function now:

>>> print 'something\t', 'other'
something       other
>>> print 'something\tother'
something       other

Note how the above outputs are exactly equivalent even though the first one used comma. This is because the comma doesn't introduce whitespace in certain situations (e.g. right after a tab or a newline).

In python3 this doesn't happen:

>>> print('something\t', 'other')
something        other
>>> print('something\tother')  # note the difference in spacing.
something       other

Since python2.6 the preferred way of doing string formatting is using the str.format method. It was meant to replace the %-style formatting, even though currently there are no plans (and I don't there will ever be) to remove %-style formatting.

the question is, wether you want print variables (case 1) or want to output formatted text (case 2). Case one is good and easy to use, mostly for debug output. If you like to say something in a defined way, formatting is the better choice. '+' is not the pythonic way of string maipulation.

An alternative to % is "{0} to the {1}".format(a,b) and is the preferred way of formatting since Python 3.

Depends a bit on which version.

Python 2 will be simply:

print 'string'
print 345
print 'string'+(str(345))
print ''

Python 3 requires parentheses (wish it didn't personally)

print ('string')
print (345)
print ('string'+(str(345))

Also the most foolproof method to do it is to convert everything into a variable:

a = 'string'
b = 345
c = str(345)
d = a + c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top