str % .. accepts a tuple as a right-hand operand, so you can do the following:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
Your try should work in Python 3, where Additional Unpacking Generalizations is supported, but not in Python 2.x:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
Answer from falsetru on Stack Overflowstr % .. accepts a tuple as a right-hand operand, so you can do the following:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
Your try should work in Python 3, where Additional Unpacking Generalizations is supported, but not in Python 2.x:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
Perhaps have a look at str.format().
>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'
Update:
For completeness I am also including additional unpacking generalizations described by PEP 448. The extended syntax was introduced in Python 3.5, and the following is no longer a syntax error:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {}'
>>> template.format(*x, y) # valid in Python3.5+
'first: 5, second: 7, last: 42'
In Python 3.4 and below, however, if you want to pass additional arguments after the unpacked tuple, you are probably best off to pass them as named arguments:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {last}'
>>> template.format(*x, last=y)
'first: 5, second: 7, last: 42'
This avoids the need to build a new tuple containing one extra element at the end.
Do you normally use string.format() or percentage (%) to format your Python strings?
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
More on reddit.comescaping - How can I selectively escape percent (%) in Python strings? - Stack Overflow
python - How do I print a '%' sign using string formatting? - Stack Overflow
Python format string for percentage with space before % - Stack Overflow
What is the standard way to print a literal percent sign using Python's % formatting
Do I need to escape the percent sign in Python 3 f-strings
How to print a literal curly brace in .format() or f-strings
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now:
"Today is %s." % datetime.now() # 2018-06-03 16:50:35.226194 "%d is a good number." % 5 # 5
I know this may not be very eloquent, but does the job well. One of the major irritants for me is the number to string conversion, I've faced that error so many times in the earlier days when I simply used to "There are " + x + " mangoes.". This works great in most other languages as they "auto-convert" the x from integer to string, but not python because of its "explicitness". But today, I learned of this new method of string.format() which does the same job, perhaps more eloquently:
"Today is {0}.".format(datetime.now()) # 2018-06-03 16:50:35.226194
"{0} is a good number.".format(5) # 5The only problem I'd imagine would be when you have to deal with long floats:
f = 1.234535666
"this is a floating point number: {0}".format(f) # 1.234535666Problem here is that it will output the entire float as it is without rounding, and here is where my percentage method has an edge!
"this is a floating point number: %.2f" % f # 1.23
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
of course .format() can do number formatting - "a number {:.2f}"! also you don't have to use explicit {0} indexing, you can go by position {} or use labels {a}.
https://docs.python.org/3.4/library/string.html#format-examples
You just discovered .format()? people are mostly migrating away from that to fstrings if they are using modern versions.
dude, you have to read the docs
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
Alternatively, as of Python 2.6, you can use new string formatting (described in PEP 3101):
'Print percent % in sentence and not {0}'.format(test)
which is especially handy as your strings get more complicated.
To print the % sign you need to 'escape' it with another % sign:
percent = 12
print "Percentage: %s %%\n" % percent # Note the double % sign
>>> Percentage: 12 %
EDIT
Nowadays in python3 a better (and more readable) approach is to use f-strings. Note that other solutions (shown below) do work as well:
$python3
>>> percent = 12
>>> print(f'Percentage: {percent}%') # f-string
Percentage: 12%
>>> print('Percentage: {0}%'.format(percent)) # str format method
Percentage: 12%
>>> print('Percentage: %s%%' % percent) # older format, we 'escape' the '%' character
Percentage: 12%
Or use format() function, which is more elegant.
percent = 12
print "Percentage: {}%".format(percent)
4 years later edit
Now In Python3x print() requires parenthesis.
percent = 12
print ("Percentage: {}%".format(percent))
To be honest as a lazy programmer myself I would just use str.replace (https://docs.python.org/3/library/stdtypes.html#str.replace) after the formatting appended like this:
a = '{:.1%}'.format(0.331).replace('%', ' %')
print(a)
gives: 33.1 %
You can use f'' strings:
num = .331
print(f'the percent is {num*100:6.2f} %')
percent is 33.10 %
https://realpython.com/python-f-strings/
Since Python 3.0, str.format and format support a percentage presentation type:
>>> f"{1/3:.0%}"
'33%'
>>> "{:.0%}".format(1/3)
'33%'
>>> format(1/3, ".0%")
'33%'
Percentage. Multiplies the number by 100 and displays in fixed (
'f') format, followed by a percent sign.
The .0 part of the format spec .0% indicates that you want zero digits of precision after the decimal point, because with f"{1/3:%}" you would get the string '33.333333%'.
It works with integers, floats, and decimals. See PEP 3101.
There is a way more convenient 'percent'-formatting option for the .format() format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'