%s
在 Python 中是什么意思?下面这段代码有什么作用?
比如……
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 中借用的)。
请参阅 "PyFormat" :
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.
这是一个非常简单的例子:
#Python 2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python 3+
name = input("who are you? ")
print("hello %s" % (name,))
%s
标记允许我插入(并可能格式化)字符串。请注意,%s
标记被我在 %
符号之后传递给字符串的任何内容替换。另请注意,我在这里也使用了一个元组(当您只有一个字符串时,使用元组是可选的)来说明可以在一个语句中插入多个字符串并对其进行格式化。
https://stackoverflow.com/questions/997797/