python - Python 格式字符串中的 %s 是什么意思?

%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/

相关文章:

python - Python 中的 '@=' 符号是什么?

python - 将 datetime 转换为 Unix 时间戳并将其转换回 python

python - Python 'for' 循环中的范围

linux - 如何以正确的方式关闭 Spring Boot 应用程序?

python - "inconsistent use of tabs and spaces in i

python - 如何将 NumPy 数组标准化为单位向量?

linux - 在 sudo 调用的 Bash 脚本中识别用户

c - 硬 float 和软 float 有什么区别?

c - 从C中的文件描述符中检索文件名

linux - grep 排除多个字符串