【问题标题】:What does %s mean in a Python format string?Python 格式字符串中的 %s 是什么意思?
【发布时间】:2022-04-08 05:03:16
【问题描述】:

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

【问题讨论】:

  • 不推荐使用% 运算符,取而代之的是更强大的str.format 方法,请参阅PEP-3101。
  • 实际上 PEP 说“在 Python 3.0 中,% 运算符由更强大的字符串格式化方法补充”,并且它被向后移植到 Python 2.6。我来自哪里“补充”意味着添加,而不是替换。 PEP 没有说“被取代”,并且在 PEP 的任何部分都没有说 % 运算符已被弃用(但它确实说其他东西在底部已被弃用)。您可能更喜欢 str.format ,这很好,但在 PEP 说它已被弃用之前,声称它不被弃用是没有意义的。

标签: python string-formatting


【解决方案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 方法。
  • 在 python3 中,raw_input() 现在只是 input() 对于那些为自己努力的人。
【解决方案2】:

Andrew's answer 不错。

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

"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

【讨论】:

  • 不错。 %d 使您免于转换 str(int)。知道 %s 和 %d 代表什么吗?我想我会以字符串和数字的形式记住它们。
  • @user391339 代表十进制 :) 他们都在这里docs.python.org/2/library/…
  • 我不知道早期版本,但至少对于 3.6,即使您在整数上使用 %s,它也可以正常工作,它只会被转换为字符串。
  • @lapin 你是对的 :) 。但这可能并不总是您想要的。例如,假设您想填充一个数字。 print('This number will be padded with 4 zeros: %05d ' % 1) - 这行得通。 print('This number will be padded with 4 zeros: %05s ' % 1) - 这不会`
  • @sqram 嗨,有没有办法在不改变输入中 john 和 mike 的位置的情况下改变 John 和 mike 的位置?
【解决方案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'

【讨论】:

  • 如果它解释问题中的语法是格式化文本并且 then 演示了较新的方法,则会改进此答案。这样它就可以独立存在。提供与问题中的示例等效的示例也是一个加分项。
【解决方案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 的字符串格式化功能时的转换类型为 string。更具体地说,%s 使用str() 函数将指定值转换为字符串。将此与使用repr() 函数进行值转换的%r 转换类型进行比较。

    看看documentation for string formatting。

    【讨论】:

      【解决方案6】:

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

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

      所以第一个if 语句转换为:如果你还没有传递给我一个参数,我会告诉你你以后应该如何传递给我一个参数,例如你会在屏幕上看到这个:

      Usage: myscript.py database-name
      

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

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

      来自the documentation:

      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.
        

        【讨论】:

          猜你喜欢
          • 2018-08-03
          • 1970-01-01
          • 2018-08-28
          • 2010-11-03
          • 2021-11-25
          • 2019-03-03
          • 1970-01-01
          • 2017-12-01
          • 1970-01-01
          相关资源
          最近更新 更多