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?

+3


source to share


3 answers


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.

0


source


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.

-1


source


The plus if it's a string is a join, and you might recommend using STR. Format (* argw, * * kw) to change

-2


source







All Articles