简体   繁体   中英

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 a string and passing in the value after?

site = "Stackoverflow"
site + " is great!"

"%s is great!" % "Stackoverflow"

Printing either of these gives the same result so when is it better to use one over the other?

If you want to keep certain string constants in the same file, or on the top most of the file, you can declare the string with the placeholders as constants, then replace the placeholders with actual variable at run time through the % syntax.

This also allows greater re-usability. Eg. you can store a single constant "%s is %s years old" .

Using this syntax might also make the string more readable.

For two strings, there is little difference.

For multiple strings, s1 + s2 + s3 is less efficient, as it has to create a temporary str object for the first concatenation, where as both "%s %s %s" % (s1, s2, s3) and "{} {} {}".format(s1, s2, s3) creates the final str object immediately.

One:

'string' + 'string'


Two:

'%s %s' % ('one', 'two')
'{} {}'.format('one', 'two')

There is a great article on this here: https://pyformat.info/

Also the docs are a great resource: https://docs.python.org/2/library/string.html#format-string-syntax

Version one is less efficient with larger amounts of concatenation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM