Home » Python » Using Python String Formatting with Lists

Using Python String Formatting with Lists

Posted by: admin November 30, 2017 Leave a comment

Questions:

I construct a string s in Python 2.6.5 which will have a varying number of %s tokens, which match the number of entries in list x. I need to write out a formatted string. The following doesn’t work, but indicates what I’m trying to do. In this example, there are three %s tokens and the list has three entries.

s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)

I’d like the output string to be:

1 BLAH 2 FOO 3 BAR

Answers:
print s % tuple(x)

instead of

print s % (x)

Questions:
Answers:

You should take a look to the format method of python. You could then define your formatting string like this :

>>> s = '{0} BLAH {1} BLAH BLAH {2} BLAH BLAH BLAH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH 2 BLAH BLAH 3 BLAH BLAH BLAH'

Questions:
Answers:

Following this resource page, if the length of x is varying, we can use:

', '.join(['%.2f']*len(x))

to create a place holder for each element from the list x. Here is the example:

x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]

Questions:
Answers:

Since I just learned about this cool thing(indexing into lists from within a format string) I’m adding to this old question.

s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print s.format (x=x)

However, I still haven’t figured out how to do slicing(inside of the format string '"{x[2:4]}".format...,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.

Questions:
Answers:

This was a fun question! Another way to handle this with the .format method for variable length lists is to use a function that takes full advantage of list unpacking. In the following example I don’t use any fancy formatting, but that can easily be changed to suit your needs.

list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]

# Create a function to easily repeat on many lists:
def ListToFormattedString(alist):
    # Each item is right-adjusted, width=3
    formatted_list = ['{:>3}' for item in alist] 
    s = ','.join(formatted_list)
    return s.format(*alist)

# Example output:
>>>ListToFormattedString(list_1)
'  1,  2,  3,  4,  5,  6'
>>>ListToFormattedString(list_2)
'  1,  2,  3,  4,  5,  6,  7,  8'