在Python中,%对字符串有什么作用?
%既是一个字符串格式化运算符,也是插值运算符。 给定format%values(其中format是字符串),format中的%转换规范将被值的零个或多个元素替换。 效果类似于在C语言中使用sprintf()。 例如,
>>> lang = "Python"
>>> print "%s is awesome!" % lang
Python is awesome
您还可以使用此符号格式化数字。 例如,
>>> cost = 128.527
>>> print "The book costs %.2f at the bookstore" % cost
The book costs128.53 at the bookstore
您还可以使用字典插入字符串。他们有一种语法,在%和转换字符之间的括号中提供密钥即可。 例如,
print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.
您可以在此处了解更多有关字符串格式化及其运算符的信息: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
更多Python相关文章,请阅读:Python 教程
极客教程