lynn8570
lynn8570

Reputation: 1683

how to replace %s with one variable in python

I have a string like

strTemp='i don\'t want %s repeat the %s variable again %s and again %s'%('aa','aa','aa','aa')

I want to replace all the %s with 'aa', so I have to repeat the 'aa' for many times, how can I tell the program that I want to replace all the %s just with the same variable, so I needn't type the variable for times

Upvotes: 3

Views: 5851

Answers (3)

Don Question
Don Question

Reputation: 11614

if you have really many repetitions and don't want to type {0} or %(var)s you may consider a seldom used (placeholder-)char, which gets replaced, e.g.:

p='µ µµ µµµ µµµµ µµµµµ {1}'.replace('µ','{0}').format(' muahaha ', 'duh')

or for a single substition variable:

strTemp='i don\'t want µ repeat the µ variable again µ and again µ'.replace('µ','aa')

Upvotes: 0

Antimony
Antimony

Reputation: 39451

The % operator is discouraged. Use str.format instead.

strTemp='i don\'t want {0} repeat the {0} variable again {0} and again {0}'.format('aa')

Upvotes: 7

Platinum Azure
Platinum Azure

Reputation: 46193

You could use the named formatting argument syntax:

strTemp='i don\'t want %(key)s repeat the %(key)s variable again %(key)s and again %(key)s' % {
    'key': 'replacement value',
}

Not a lot better necessarily since you have to repeat a key four times, but if your replacement value is long, or is a calculation with side effects that you really don't want to do more than once, this is a good option.

Upvotes: 7

Related Questions