Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string formatting with percent sign

Tags:

I am trying to do exactly the following:

>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'

However, I have a long x, more than two items, so I tried:

>>> '%d,%d,%s' % (*x, y)

but it is syntax error. What would be the proper way of doing this without indexing like the first example?

like image 245
Sait Avatar asked Aug 12 '15 12:08

Sait


People also ask

How do you put a percent sign in a string in Python?

The %s signifies that you want to add string value into the string, it is also used to format numbers in a string. After writing the above code (what does %s mean in python), Ones you will print ” string “ then the output will appear as a “ Variable as string = 20 ”.

How do you add a percent sign in string format?

You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.

How do you use %d and %s in Python?

In, Python %s and %d are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator. This code will print abc 2.

How do I show a percentage sign in Python?

Using %% Character to Escape Percent Sign in Python See the code below. By using the percentage sign twice ( %% ), we can overcome the error. However, if we are not using any specifier, this will print the percentage sign twice only.


2 Answers

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'
like image 144
falsetru Avatar answered Sep 22 '22 02:09

falsetru


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.

like image 30
plamut Avatar answered Sep 21 '22 02:09

plamut