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

211

在Python中,%s是什么意思?以下这段代码又是做什么用的呢?

例如...

 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])

5
%运算符已被弃用,建议使用更为强大的str.format方法。请参见PEP-3101 - Paulo Scardine
50
实际上,那个PEP说:“在Python 3.0中,%运算符被一个更强大的字符串格式化方法所补充”,并且它被移植到Python 2.6。在我来自的地方,“补充”意味着添加,而不是替换。这个PEP没有说“取代”,在整个PEP的任何部分中也没有说%运算符被废弃(但底部确实说了其他一些东西被废弃)。你可能更喜欢使用str.format,这是可以接受的,但在没有PEP声明它被弃用之前,声称它被弃用是没有意义的。 - Ben
8个回答

249

这是一种字符串格式化语法(它从C语言借鉴而来)。

请参阅"PyFormat"

Python支持将值格式化为字符串。尽管这可能包括非常复杂的表达式,但最基本的用法是使用%s占位符将值插入到字符串中。

这里有一个非常简单的示例:

#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标记会被替换为我传递给字符串的任何内容。还要注意,我在这里也使用了一个元组(当只有一个字符串时,使用元组是可选的),以说明可以在一条语句中插入和格式化多个字符串。


15
请注意,这种字符串插值的方法已经被弃用,建议改用更强大的 str.format 方法。 - Paulo Scardine
8
在Python3中,raw_input()现在被改成了input()。这是给那些自学的人提醒。 - Peter Girnus
哈哈。@PauloScardine 更强大?格式化字符串:f'{}' 进入聊天室。 - undefined

153

安德鲁的回答很好。

此外,为了更好地帮助您,以下是如何在一个字符串中使用多个格式化的示例:

"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
如果你使用的是整数而不是字符串,请使用 %d 而不是 %s。
"My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12

2
不错。 %d 可以避免强制转换 str(int)。你知道 %s 和 %d 代表什么吗?我猜我会把它们记作字符串和数字。 - user391339
5
@user391339 代表十进制数 :) 它们全部在这里 https://docs.python.org/2/library/stdtypes.html#string-formatting-operations - sqram
1
我不知道早期版本如何,但至少对于3.6版本,即使在整数上使用“%s”,它的工作方式也是相同的,它只会被转换为字符串。 - lapin
1
@lapin 你说得对 :) 。但这并不总是你想要的。比如说你想填充一个数字。print('This number will be padded with 4 zeros: %05d ' % 1) - 这个会起作用。print('This number will be padded with 4 zeros: %05s ' % 1) - 这个则不会。 - sqram
@sqram 你好,有没有办法在不改变输入中John和Mike的位置的情况下改变他们的位置? - Imtango30

36

format方法是Python2.6引入的。它更强大,使用起来也不太困难:

>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.

>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'

>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'

>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'

12
如果解释问题中的语法是格式化文本,然后演示新方法,这个答案将会更好。这样它就可以独立存在了。提供一个与问题中示例等效的示例也将是一个优点。 - Steve S

28

%s%d是格式说明符或用于格式化字符串、十进制、浮点数等的占位符。

最常用的格式说明符:

%s:字符串

%d:十进制数

%f:浮点数

自说明代码:

name = "Gandalf"
extendedName = "the Grey"
age = 84
IQ = 149.9
print('type(name): ', type(name)) # type(name): <class 'str'>
print('type(age): ', type(age))   # type(age): <class 'int'>
print('type(IQ): ', type(IQ))     # type(IQ): <class 'float'>

print('%s %s\'s age is %d with incredible IQ of %f ' %(name, extendedName, age, IQ)) # Gandalf the Grey's age is 84 with incredible IQ of 149.900000

# The same output can be printed in following ways:


print ('{0} {1}\'s age is {2} with incredible IQ of {3} '.format(name, extendedName, age, IQ))          # With the help of an older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ))          # With the help of an older method

print("Multiplication of %d and %f is %f" %(age, IQ, age*IQ)) # Multiplication of 84 and 149.900000 is 12591.600000

# Storing formattings in a string

sub1 = "python string!"
sub2 = "an arg"

a = "I am a %s" % sub1
b = "I am a {0}".format(sub1)

c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)

print(a)  # "I am a python string!"
print(b)  # "I am a python string!"
print(c)  # "with an arg!"
print(d)  # "with an arg!"

14

%s 表示在使用Python的字符串格式化功能时,转换类型为字符串。更具体地说,%s 使用str()函数将指定的值转换为字符串。与之对比的是%r转换类型,它使用repr()函数进行值转换。

请参阅字符串格式化操作的文档


7
回答你的第二个问题:这段代码是干什么用的?...
这是一个Python脚本的标准错误检查代码,该脚本接受命令行参数。
因此,第一个`if`语句的意思是:如果你没有传递给我一个参数,我会告诉你未来应该如何传递给我一个参数,例如,你将在屏幕上看到这个信息:
Usage: myscript.py database-name

下一个if语句检查您传递给脚本的“database-name”是否实际存在于文件系统中。如果不存在,则会收到如下消息:

错误:未找到数据库 database-name!

来自文档

argv [0]是脚本名称(这取决于操作系统是否为完整路径名)。如果使用-c命令行选项执行命令,则argv [0]设置为字符串“-c”。如果没有将脚本名称传递给Python解释器,则argv [0]为空字符串。


3

这里有一个Python 3的好例子。

>>> a = input("What is your name? ")
What is your name? Peter

>>> b = input("Where are you from? ")
Where are you from? DE

>>> print("So you are %s of %s." % (a, b))
So you are Peter of DE.

-1
正如其他答案所提到的那样:在字符串格式化中使用了`%s`操作符。
尽管从Python 3.6及以上版本开始,引入了一种更直观的字符串格式化语法,称为`f-string`。 来源
full_name = 'Foo Bar'
print(f'My name is {full_name}')

# Output: My name is Foo Bar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接