%s在python格式字符串中是什么意思?


166

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

4
%运营商的支持更强大的过时str.format的方法,请参阅PEP-3101
Paulo Scardine

35
实际上,PEP表示“在Python 3.0中,%运算符由更强大的字符串格式化方法进行了补充”,并且它已反向移植到Python 2.6。我来自哪里,“补充”是指添加,而不是替换。PEP不会说“已取代”,并且在PEP的任何部分都没有说过%运算符(但它确实说其他事情从底部开始不赞成使用)。您可能更喜欢str.format,这很好,但是直到有一个PEP声明它已被弃用,才没有理由断言它不是。

Answers:


198

这是一种字符串格式语法(它是从C借用的)。

请参阅“ PyFormat”

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

编辑:这是一个非常简单的示例:

#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)

#Python3+
name = input("who are you? ")
print("hello %s" % (name,))

%s令牌允许我插入(和潜在的格式)的字符串。请注意,%s令牌被替换为%符号后传递给字符串的任何内容。还要注意,我也在这里使用一个元组(当您只有一个字符串时,使用元组是可选的),以说明可以在一个语句中插入多个字符串并设置其格式。


11
请注意,不建议使用这种字符串内插方法,而应使用功能更强大的str.format方法。
Paulo Scardine

6
在python3中,raw_input()现在只是为那些自己尝试的人提供的input()。
Gothburz

1
为什么(name,),而不仅仅是name
卡梅伦·哈德森

111

安德鲁的答案很好。

为了进一步帮助您,以下是在一个字符串中使用多种格式的方法

"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 '16

1
@ user391339代表十进制:)它们都在这里docs.python.org/2/library/…–
sqram

我不知道较早的版本,但至少对于3.6,即使您使用%s整数,它的工作原理也一样,它将被转换为字符串。
拉皮

@lapin你是正确的:)。但这可能并不总是您想要的。例如,假设您要填充数字。print('This number will be padded with 4 zeros: %05d ' % 1)-可以。print('This number will be padded with 4 zeros: %05s ' % 1)-这不会`
sqram

28

format方法在Python 2.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'

11
如果它说明问题中的语法正在格式化文本,然后演示了较新的方法,则将可以改善此答案。这样,它就可以独立存在。提供一个与问题中的示例相同的示例也是一个加号。
史蒂夫·S

13

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

看一下用于字符串格式化文档


13

%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 

#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 help of older method
print ('{} {}\'s age is {} with incredible IQ of {} '.format(name, extendedName, age, IQ))          # with help of 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 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!"

6

在回答您的第二个问题:此代码有什么作用?...

这是用于接受命令行参数的Python脚本的相当标准的错误检查代码。

因此,第一个if语句的意思是:如果您还没有给我一个论点,我将告诉您将来应该如何给我一个论点,例如,您将在屏幕上看到以下内容:

Usage: myscript.py database-name

if一条语句检查以查看传递给脚本的“数据库名称”在文件系统上是否实际存在。如果没有,您将收到以下消息:

ERROR: Database database-name was not found!

文档中

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


2

这是Python3中的一个很好的例子。

  >>> 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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.