首页 > 解决方案 > 为什么后来 double %% 转换为 single %

问题描述

l='a'     
r='%sbb%%'%l    
print(r)

我期望输出abb%%,但实际输出是abb%
有人可以解释为什么吗?

标签: pythonstring-formatting

解决方案


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

输入:

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               |
+------+----------------------------------------------+

推荐阅读