Fix Python – Inserting the same value multiple times when formatting a string

Question

Asked By – Goutham

I have a string of this form

s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)

All the %s in string have the same value (i.e. s).
Is there a better way of writing this? (Rather than listing out s three times)

Now we will see solution for issue: Inserting the same value multiple times when formatting a string


Answer

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

This question is answered By – Adam Rosenfield

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0