Python 格式字符串中的 %s 是什么意思?

发布于 2024-07-24 07:42:42 字数 276 浏览 7 评论 0原文

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

What does %s mean in 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])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

遇到 2024-07-31 07:42:42

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

It is a string formatting syntax (which it borrows from C).

Please see "PyFormat":

Python supports formatting values into
strings. Although this can include
very complicated expressions, the most
basic usage is to insert values into a
string with the %s placeholder.

Here is a really simple example:

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

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

The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. 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.

森罗 2024-07-31 07:42:42

安德鲁的回答很好。

为了帮助您多一点,这里介绍了如何在一个字符串中使用多种格式:

"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

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.

"My name is %s and I'm %d" % ('john', 12) #My name is john and I'm 12
不再让梦枯萎 2024-07-31 07:42:42

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'

The format method was introduced in 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'
上课铃就是安魂曲 2024-07-31 07:42:42

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

%sand %d are format specifiers or placeholders for formatting strings, decimals, floats, etc.

The most common used format specifiers:

%s: string

%d: decimals

%f: float

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

# 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!"
红颜悴 2024-07-31 07:42:42

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

查看字符串格式化文档

%s indicates a conversion type of string when using Python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the documentation for string formatting.

撩动你心 2024-07-31 07:42:42

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

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

因此,第一个 if 语句翻译为:如果你还没有向我传递一个参数,我将告诉你将来应该如何向我传递一个参数,例如你会在-screen:

Usage: myscript.py database-name

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

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

来自文档

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

To answer your second question: What does this code do?...

This is fairly standard error-checking code for a Python script that accepts command-line arguments.

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, e.g. you'll see this on-screen:

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 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). If
the command was executed using the -c
command line option to the
interpreter, argv[0] is set to the
string '-c'. If no script name was
passed to the Python interpreter,
argv[0] is the empty string.

微暖i 2024-07-31 07:42:42

这是 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.

Here is a good example in 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.
衣神在巴黎 2024-07-31 07:42:42

正如其他答案正确提到的: %s 运算符用于字符串格式化。

尽管从 Python 3.6 及更高版本开始,引入了一种更直观的字符串格式化语法,称为 f-string

来源

full_name = 'Foo Bar'
print(f'My name is {full_name}')

# Output: My name is Foo Bar

As the other answers rightfully mentioned: The %s operator is used in string formatting.

Although as from Python 3.6 and above, a more intuitive string formatting syntax is introduced, called the f-string.

Source

full_name = 'Foo Bar'
print(f'My name is {full_name}')

# Output: My name is Foo Bar
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文