197

%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

7 回答 7

236

它是一种字符串格式化语法(它从 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令牌被我在%符号后面传递给字符串的任何内容所替换。另请注意,我在这里也使用了一个元组(当您只有一个字符串时,使用元组是可选的)来说明可以在一个语句中插入多个字符串并对其进行格式化。

于 2009-06-15T19:06:11.830 回答
137

安德鲁的回答很好。

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

"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
于 2009-06-15T20:17:14.197 回答
33

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'
于 2013-07-17T17:50:53.563 回答
21

%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!"
于 2018-08-07T11:34:50.870 回答
14

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

查看有关字符串格式化的文档

于 2009-06-15T19:09:30.623 回答
7

回答你的第二个问题:这段代码有什么作用?...

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

所以第if一句话翻译成:如果你还没有传递给我一个参数,我会告诉你将来你应该如何传递给我一个参数,例如你会在屏幕上看到这个:

Usage: myscript.py database-name

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

错误:找不到数据库数据库名称!

文档中

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

于 2009-06-15T19:15:47.037 回答
3

这是 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
于 2018-06-03T18:43:28.787 回答