Python 格式字符串中的 %s 含义是什么?
- 2025-01-15 08:46:00
- admin 原创
- 122
问题描述:
在 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])
解决方案 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
将被我传递给符号后面的字符串的任何内容替换%
。还请注意,我在这里也使用了一个元组(当您只有一个字符串时,使用元组是可选的),以说明可以在一个语句中插入和格式化多个字符串。
解决方案 2:
安德鲁的回答很好。
为了给您提供更多帮助,以下是如何在一个字符串中使用多种格式:
"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
解决方案 3:
该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'
解决方案 4:
%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!"
解决方案 5:
%s
表示使用 Python 的字符串格式化功能时字符串的转换类型。更具体地说,%s
使用函数将指定值转换为字符串str()
。将其与%r
使用repr()
函数进行值转换的转换类型进行比较。
查看字符串格式的文档。
解决方案 6:
回答你的第二个问题:这段代码有什么作用?...
对于接受命令行参数的 Python 脚本来说,这是相当标准的错误检查代码。
因此,第一条if
语句的意思是:如果您还没有向我传递参数,我将告诉您将来应该如何向我传递参数,例如,您将在屏幕上看到以下内容:
Usage: myscript.py database-name
下一个if
语句检查您传递给脚本的“数据库名称”是否确实存在于文件系统中。如果不存在,您将收到如下消息:
错误:未找到数据库数据库名称!
来自文档:
argv[0] 是脚本名称(这是否是完整路径名取决于操作系统)。如果使用解释器的 -c 命令行选项执行命令,则 argv[0] 设置为字符串“-c”。如果没有将脚本名称传递给 Python 解释器,则 argv[0] 为空字符串。
解决方案 7:
这是 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.
解决方案 8:
正如其他答案正确提到的那样:该%s
运算符用于字符串格式化。
尽管从 Python 3.6 及更高版本开始,引入了一种更直观的字符串格式化语法,称为f-string
。
来源
full_name = 'Foo Bar'
print(f'My name is {full_name}')
# Output: My name is Foo Bar
扫码咨询,免费领取项目管理大礼包!