简体   繁体   English

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

[英]What does %s mean in a python format string?

What does %s mean in Python? %s在 Python 中是什么意思? And what does the following bit of code do?下面的代码有什么作用?

For instance...例如...

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

It is a string formatting syntax (which it borrows from C).它是一种字符串格式化语法(它是从 C 中借来的)。

Please see "PyFormat" :请参阅“PyFormat”

Python supports formatting values into strings. Python 支持将值格式化为字符串。 Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.尽管这可能包括非常复杂的表达式,但最基本的用法是将值插入带有%s占位符的字符串中。

Edit: Here is a really simple example:编辑:这是一个非常简单的例子:

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

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

The %s token allows me to insert (and potentially format) a string. %s标记允许我插入(并可能格式化)一个字符串。 Notice that the %s token is replaced by whatever I pass to the string after the % symbol.请注意, %s标记被我在%符号后传递给字符串的任何内容替换。 Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.另请注意,我在这里也使用了元组(当您只有一个字符串时,使用元组是可选的)来说明可以在一个语句中插入和格式化多个字符串。

Andrew's answer is good.安德鲁的回答很好。

And just to help you out a bit more, here's how you use multiple formatting in one string只是为了帮助您更多,这里是您如何在一个字符串中使用多种格式

"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".

If you are using ints instead of string, use %d instead of %s.如果您使用整数而不是字符串,请使用 %d 而不是 %s。

"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12

The format method was introduced in Python 2.6. format方法是在 Python 2.6 中引入的。 It is more capable and not much more difficult to use:它功能更强大,使用起来也不难:

>>> "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 and %d are Format Specifiers or placeholders for formatting strings/decimals/floats etc. %s%d是用于格式化字符串/小数/浮点数等的格式说明符或占位符。

MOST common used Format specifier:常用的格式说明符:

%s : string %s : 字符串

%d : decimals %d : 小数

%f : float %f : 浮动

Self explanatory code:自解释代码:

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!"

%s indicates a conversion type of string when using python's string formatting capabilities. %s表示使用python的字符串格式化功能时字符串的转换类型。 More specifically, %s converts a specified value to a string using the str() function.更具体地说, %s使用str()函数将指定值转换为字符串。 Compare this with the %r conversion type that uses the repr() function for value conversion.将此与使用repr()函数进行值转换的%r转换类型进行比较。

Take a look at the docs for string formatting .查看字符串格式文档

In answer to your second question: What does this code do?...回答你的第二个问题:这段代码有什么作用?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.这是接受命令行参数的 Python 脚本的相当标准的错误检查代码。

So the first if statement translates to: if you haven't passed me an argument, I'm going to tell you how you should pass me an argument in the future, eg you'll see this on-screen:所以第一个if语句转换为:如果你还没有给我传递一个参数,我将告诉你你将来应该如何传递一个参数,例如你会在屏幕上看到这个:

Usage: myscript.py database-name

The next if statement checks to see if the 'database-name' you passed to the script actually exists on the filesystem.下一个if语句检查您传递给脚本的“数据库名称”是否确实存在于文件系统中。 If not, you'll get a message like this:如果没有,您将收到如下消息:

ERROR: Database database-name was not found!

From the documentation :文档

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). argv[0] 是脚本名称(它是否为完整路径名取决于操作系统)。 If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'.如果命令是使用解释器的 -c 命令行选项执行的,则 argv[0] 设置为字符串“-c”。 If no script name was passed to the Python interpreter, argv[0] is the empty string.如果没有脚本名称传递给 Python 解释器,则 argv[0] 是空字符串。

Here is a good example in Python3.这是 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM