What does % do to strings in Python? [closed]

大憨熊 提交于 2019-11-26 22:48:33
Konrad Rudolph

It's the string formatting operator. Read up on string formatting in Python.

format % values

Creates a string where format specifies a format and values are the values to be filled in.

It applies printf-like formatting to a string, so that you can substitute certain parts of a string with values of variables. Example

# assuming numFiles is an int variable
print "Found %d files" % (numFiles, )

See the link provided by Konrad

The '%' operator is used for string interpolation. Since Python 2.6 the String method "format" is used insted. For details see http://www.python.org/dev/peps/pep-3101/

Note that starting from Python 2.6, it's recommended to use the new str.format() method:

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

If you are using 2.6, you may want to keep using % in order to remain compatible with older versions, but in Python 3 there's no reason not to use str.format().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!