%s 在 python 格式字符串中是什么意思? [英] What does %s mean in a python format string?
问题描述
%s
在 Python 中是什么意思?下面这段代码有什么作用?
What does %s
mean in Python? And what does the following bit of code do?
例如...
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
推荐答案
它是一种字符串格式化语法(从 C 中借用).
It is a string formatting syntax (which it borrows from C).
请参阅"PyFormat":
Python 支持将值格式化为字符串.虽然这可以包括非常复杂的表达,最基本用法是将值插入到带有 %s
占位符的字符串.
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the
%s
placeholder.
这是一个非常简单的例子:
Here is a really simple example:
#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python3+
name = input("who are you? ")
print("hello %s" % (name,))
%s
标记允许我插入(并可能格式化)一个字符串.请注意,%s
标记被我在 %
符号之后传递给字符串的任何内容替换.另请注意,我在这里也使用了元组(当您只有一个字符串时,使用元组是可选的)来说明可以在一个语句中插入和格式化多个字符串.
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
这篇关于%s 在 python 格式字符串中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!