-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.

2
  • You mean interrupted in terms of your typing flow? Jul 3, 2014 at 16:48
  • This is not a duplicate. Format is just one of the many possible ways to do a string. Other options like concatenation are an option for this question. Or perhaps something based around string.join Jul 3, 2014 at 16:54

1 Answer 1

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.'
>>>
1
  • 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 3, 2014 at 17:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.