How to put values of a list into a string
I am trying to place several values from a list into a string. The code I have is below:
ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}开发者_StackOverflow.'.format(ID)
or
print (r'(ID\s*=\s*)(\S+)').format(ID)
This does not work. Does anyone know where I'm going wrong. The code in the second line prints out the list:
[0, 1, 2]
the first line says:
File "tset.py", line 39, in b
print 'ID {0}, {1}, and {2}.'.format(ID)
IndexError: tuple index out of range
Thanks
You have to unpack the list.
ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(*ID)
See the docs: Unpacking argument lists.
>>> 'ID {0}, {1}, and {2}.'.format(*ID)
'ID 0, 1, and 2.'
You need to unpack your list.
Your second code doesn't make much sense.
精彩评论