3

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

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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')

6 Comments

The {} syntax is newer and spiffier. You can do a bunch of things with it that you can't with the % syntax. And I am under the impression the % syntax was removed from Python 3 but that may be wrong.
{} is definitely more powerful, but I don't see how that results in % being discouraged.
@Tim docs.python.org/2/library/stdtypes.html#str.format says "[.format()] is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code."
Faster than I expected, both the two methods are feasible, and I want to try {} syntax
@Tim, however, I was mistaken, %-style formatting does still exist in Python 3: docs.python.org/3/library/…
|
0

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')

3 Comments

For maximum compression and complete unreadability, you can use reduce to chain together lots of replacements with minimal size overhead (only need to specify the function and a list of arguments). I actually wrote a script to compress string literals this way once (it also uses other tricks to reduce size).
funny idea! ;-) but i already overstreched the OPs original intention, on the other hand it's never wrong to be reminded of such nice included batteries ;-)
@Antimony: btw i use the abilities of my editor (vim) for these superfluous typings: inoremap ¹ {0} inoremap ² {1} .... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.