views:

3306

answers:

4

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)

+4  A: 
>>> 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.

mhawke
Nice. Had forgotten about this. locals() will do as well.
Goutham
@Goutham: Adam Rosenfield's answer might be better if you're Python version is up to date.
mhawke
It is actually. Iam still getting used to the new string formatting operations.
Goutham
even better, you can multuply the base string: '%(s)s hello world '*3 % {'s': 'asdad'}
dalloliogm
+11  A: 

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)
Adam Rosenfield
A: 

Hello,

You can use the dictionary type of formatting:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}
Lucas S.
Seems to be very little point in providing this duplicate answer. Here's another one: '%(string_goes_here)s hello world %(string_goes_here)s hello world %(string_goes_here)s' % {'string_goes_here': s,}. There's practically an infinite number of possibilities.
mhawke
mhawke: i posted the message before my browser reloads the page so i didn't know at that momment that the question was already answered. You don´t need to be rude man!!.
Lucas S.
@Lucas: I suppose that it is possible that it took you 13 minutes to type in your answer :) and thanks for the down vote... much appreciated.
mhawke
+1  A: 

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,))
jjames