What's the difference between using a variable or% s in Python string formatting?
What is the difference between defining a variable and using it in a string and putting% s in the string and passing the value after?
site = "Stackoverflow"
site + " is great!"
"%s is great!" % "Stackoverflow"
Printing either one gives the same result, so when is it better to use one over the other?
source to share
If you want to keep certain string constants in a single file, or at the top of a larger portion of a file, you can declare a string with constant placeholders and then replace the actual variable placeholders at runtime via the% syntax.
It also allows for increased reuse. For example. you can keep one constant "%s is %s years old"
.
Using this syntax can also make the string more readable.
source to share
There is a slight difference for the two lines.
For multiple strings s1 + s2 + s3 is less efficient as it has to create a temporary str object for the first concatenation where both "% s% s% s"% (s1, s2, s3) and "{} {} { } ". format (s1, s2, s3) immediately creates the final str object.
One:
'string' + 'string'
Two:
'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')
There is a great article here: https://pyformat.info/
Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax
The first version is less efficient with large amounts of concatenation.
source to share