【问题标题】:What does %s" % stand for in a Python print statement [duplicate]%s" % 在 Python 打印语句中代表什么 [重复]
【发布时间】:2021-08-23 19:43:30
【问题描述】:

我一直在研究酸洗和解酸,遇到了这个问题 - 有人可以解释一下它代表什么吗?

This is the code that led to the confusion

【问题讨论】:

标签: python file


【解决方案1】:

% 表示传入字符串的参数。
%s 是应视为字符串的参数
那里还使用了一些其他类型的参数类型,例如 %d 用于十进制整数,%f 用于浮点数等。

【讨论】:

    【解决方案2】:

    %s 是使用 python 中旧格式化方法的字符串占位符。在您的示例中,基本上%smy_int 的字符串值替换。以下是@Paul Cornelius 提供的一些文档:https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

    如果您想在自己的代码中更好地工作,有一些更新的方法可以做到这一点,pickle 可能会使用旧样式,因为它们没有真正的升级理由。

    F 弦

    在 python 3.6+ 中,您可以通过在字符串声明前面放置一个 f 并使用 {variable_name} 来访问一个值来使用 fstrings。就像在这个例子中:

    name = "John Smith" # A dummy name
    
    email_count = 3 # A representation of users # of new emails
    
    current_temperature = 20.3567 # A representation of the current temperature in celsius 
    
    greeting = f"Hello, {name} The weather today is {current_temperature} degrees. You have {email_count} new emails."
    
    print(greeting)
    

    这会导致打印

    Hello John Smith The weather today is 20.3567 degrees. You have 3 new emails.

    这相当于使用 % 方法来做:

    name = "John Smith" # A dummy name
    
    email_count = 3 # A representation of users # of new emails
    
    current_temperature = 20.3567 # A representation of the current temperature in celsius 
    
    greeting = "Hello, %s The weather today is %03.2f degrees. You have %d new emails." % (name, current_temperature, email_count)
    
    print(greeting)
    

    其中%s 替换为字符串,%03.2f 替换为四舍五入到最接近的2 位小数的浮点数,%d 替换为整数。此方法被替换的主要原因之一是因为 F 字符串更易于阅读,并且不需要您提前知道放入其中的所有内容的类型(只需使用对象的 __repr__()),而例如 %d 将仅适用于整数,或者可以调用 int(obj) 的对象。

    【讨论】:

    • 仅供参考,您所说的 % 格式是绝对正确的,但它仍然是语言的一部分,并在此处记录:docs.python.org/3/library/…
    • @PaulCornelius 完美,我知道它仍然是其中的一部分,只是找不到文档,因为他们将它们从 2-3 移走了。我会更新答案,谢谢!
    猜你喜欢
    • 2017-10-03
    • 2020-04-20
    • 2017-04-05
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多