Insert the same value multiple times when formatting a string

I have a line of this form

s='arbit' string='%s hello world %s hello world %s' %(s,s,s) 

All% s in the string have the same value (i.e. s). Is there a better way to write this? (Instead of listing three times)

+93
python string format
Aug 04 '09 at 3:42
source share
6 answers

You can use the advanced string formatting available in Python 2.6 and Python 3.x:

 incoming = 'arbit' result = '{0} hello world {0} hello world {0}'.format(incoming) 
+173
Aug 04 '09 at 3:49
source share
 incoming = 'arbit' result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming} 

You may like to read this to understand: String formatting operations .

+38
Aug 04 '09 at 3:46
source share

You can use the type of dictionary formatting:

 s='arbit' string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,} 
+14
Aug. 04 '09 at 3:59
source share

Depending on what you mean, better. This works if your goal is to remove redundancy.

 s='foo' string='%s bar baz %s bar baz %s bar baz' % (3*(s,)) 
+12
Aug 04 '09 at 4:26
source share
 >>> s1 ='arbit' >>> s2 = 'hello world '.join( [s]*3 ) >>> print s2 arbit hello world arbit hello world arbit 
+3
Aug 23 '12 at 4:14
source share

Fstrings

If you are using Python 3.6+ , you can use the new so-called f-strings , which denotes formatted strings, and you can use it by adding the f character at the beginning of the line to identify it as f-string .

 price = 123 name = "Jerry" print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!") >Jerry!!, 123 is much, isn't 123 a lot? Jerry! 

The main advantages of using f-strings are that they are more readable, can be faster and offer better performance:

Pandas Source for Everyone: Python Data Analysis, Daniel Y. Chen

Benchmarks

Without a doubt, the new f-strings more readable, since you do not need to reassign the lines, but is it faster as indicated in the above quote?

 price = 123 name = "Jerry" def new(): x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!" def old(): x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name) import timeit print(timeit.timeit('new()', setup='from __main__ import new', number=10**7)) print(timeit.timeit('old()', setup='from __main__ import old', number=10**7)) > 3.8741058271543776 #new > 5.861819514350163 #old 

Running the 10 million test, it seems that the new f-strings actually works faster when matching.

+1
Dec 19 '17 at 8:51 on
source share



All Articles