【问题标题】:Why is later double %% converted to single % [duplicate]为什么后来 double %% 转换为 single % [重复]
【发布时间】:2019-10-16 23:16:40
【问题描述】:
l='a'     
r='%sbb%%'%l    
print(r)

我期望输出abb%%,但实际输出是abb%
谁能解释一下原因?

【问题讨论】:

  • 想想吧。当% 用作字符串中替换的控制字符(例如 %s)时,您需要一种方法来处理实际 % 字符。单个表示下一个字符应指示要替换的数据类型。如果下一个字符是%,则它被解释为% 字符,没有替换。

标签: python string-formatting


【解决方案1】:

百分号% 是一个特殊的元字符。我在下面描述了一些例子:

输入:

print("Hello %s %s. Your current balance is %.2f" % ("John", "Doe", 53.4423123123))
print("Hello, %s!" % "Bob")
print("%s is %d years old." % ("Sarah", 43))
print("Ian scored %.0f%s on the quiz." % (98.7337, "%"))
lyst = [1, 2, 3]
print("id(lyst) == %d" % id(lyst))
print("id(lyst) in hexadecimal format is %x" % id(lyst))

输出:

Hello John Doe. Your current balance is 53.44
Hello, Bob!
Sarah is 43 years old.
Ian scored 99% on the quiz.
id(lyst) == 58322152
id(lyst) in hexadecimal format is 379ece8

注意事项:

+------+----------------------------------------------+
| %s   | String                                       |
| %d   | Integer                                      |
| %f   | Floating point number                        |
| %.2f | float with 2 digits to the right of the dot. |
| %.4f | float with 4 digits to the right of the dot. |
| %x   | Integers in hex representation               |
+------+----------------------------------------------+

【讨论】:

  • 您的回答中没有任何部分涉及问题实际询问的情况,即%%。 (仅仅添加一个%% 示例并没有帮助,因为问题已经有一个%% 示例。您需要实际解释一下。)
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 2015-10-15
  • 1970-01-01
  • 2021-07-08
  • 2015-10-22
  • 2018-09-23
  • 2012-08-04
  • 2020-10-02
相关资源
最近更新 更多