在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])
在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])
这是一种字符串格式化语法(它从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
标记会被替换为我传递给字符串的任何内容。还要注意,我在这里也使用了一个元组(当只有一个字符串时,使用元组是可选的),以说明可以在一条语句中插入和格式化多个字符串。
str.format
方法。 - Paulo Scardinef'{}'
进入聊天室。 - undefined安德鲁的回答很好。
此外,为了更好地帮助您,以下是如何在一个字符串中使用多个格式化的示例:
"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
print('This number will be padded with 4 zeros: %05d ' % 1)
- 这个会起作用。print('This number will be padded with 4 zeros: %05s ' % 1)
- 这个则不会。 - sqramformat
方法是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'
%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!"
%s
表示在使用Python的字符串格式化功能时,转换类型为字符串。更具体地说,%s
使用str()
函数将指定的值转换为字符串。与之对比的是%r
转换类型,它使用repr()
函数进行值转换。
请参阅字符串格式化操作的文档。
Usage: myscript.py database-name
来自文档:错误:未找到数据库 database-name!
argv [0]是脚本名称(这取决于操作系统是否为完整路径名)。如果使用-c命令行选项执行命令,则argv [0]设置为字符串“-c”。如果没有将脚本名称传递给Python解释器,则argv [0]为空字符串。
这里有一个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.
full_name = 'Foo Bar'
print(f'My name is {full_name}')
# Output: My name is Foo Bar
%
运算符已被弃用,建议使用更为强大的str.format
方法。请参见PEP-3101。 - Paulo Scardine