-2

I find it takes quite a bit of focus, time an effort to format a string with the syntax I'm currently using:

myList=['one','two','three']
myString='The number %s is larger than %s but smaller than %s.'%(myList[1],myList[0],myList[2])

Result:

"The number two is larger than one but smaller than three"

Strange but every time I reach % keyboard key followed by s I feel kind of interrupted...

I wonder if there is alternative way of achieving a similar string formatting. Please post some examples.

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

1 Answers1

4

You may be looking for str.format, the new, preferred way to perform string formatting operations:

>>> myList=['one','two','three']
>>> 'The number {1} is larger than {0} but smaller than {2}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>

The main advantage of this method is that, instead of doing (myList[1],myList[0],myList[2]), you can simply unpack myList by doing *myList. Then, by numbering the format fields, you can put the substrings in the order you want.

Note too that numbering the format fields is unnecessary if myList is already in order:

>>> myList=['two','one','three']
>>> 'The number {} is larger than {} but smaller than {}.'.format(*myList)
'The number two is larger than one but smaller than three.'
>>>
  • With `str.format` you can also do indexing within the format string rather than unpacking, if you want: `"The number {0[1]} is larger than {0[0]} but smaller than {0[2]}.".format(mylist)`. – Blckknght Jul 03 '14 at 17:00