%对Python中的字符串做了什么?

Ram*_*hum 25 python string documentation operators

我没有找到运算符%的文档,因为它在Python中的字符串上使用.有人知道文档的位置吗?

Kon*_*lph 36

它是字符串格式化运算符.阅读Python中的字符串格式.

format % values
Run Code Online (Sandbox Code Playgroud)

创建一个字符串,其中format指定格式并且values是要填充的值.


Dia*_*ami 8

它将类似printf的格式应用于字符串,以便您可以使用变量值替换字符串的某些部分.例

# assuming numFiles is an int variable
print "Found %d files" % (numFiles, )
Run Code Online (Sandbox Code Playgroud)

请参阅Konrad提供的链接


小智 6

'%'运算符用于字符串插值.从Python 2.6开始,String方法"format"被用于insted.详情请见http://www.python.org/dev/peps/pep-3101/


Bas*_*ard 5

请注意,从Python 2.6开始,建议使用新str.format()方法:

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
Run Code Online (Sandbox Code Playgroud)

如果您使用2.6,您可能希望继续使用%以保持与旧版本兼容,但在Python 3中没有理由不使用str.format().

  • format()也非常强大.你可以使用像"Hello {planet}"这样的命名标签.format(planet ='earth') (3认同)