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)
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)
>>> s='arbit'
>>> string='%(s)s hello world %(s)s hello world %(s)s' % {'s': s}
>>> print string
arbit hello world arbit hello world arbit
>>>
You may like to have a read of this to get an understanding: String Formatting Operations.
You can use advanced string formatting, available in Python 2.6 and Python 3.x:
s='arbit'
string='{0} hello world {0} hello world {0}'.format(s)
Hello,
You can use the dictionary type of formatting:
s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
Depends on what you mean by better. This works if your goal is removal of redundancy.
s='foo'
string='%s bar baz %s bar baz %s bar baz' % (3*(s,))