Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace %s with one variable in python

Tags:

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

like image 363
lynn8570 Avatar asked Nov 18 '25 07:11

lynn8570


1 Answers

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.

like image 71
Platinum Azure Avatar answered Nov 20 '25 19:11

Platinum Azure



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!