【发布时间】:2019-10-16 23:16:40
【问题描述】:
l='a'
r='%sbb%%'%l
print(r)
我期望输出abb%%,但实际输出是abb%。
谁能解释一下原因?
【问题讨论】:
-
想想吧。当
%用作字符串中替换的控制字符(例如%s)时,您需要一种方法来处理实际%字符。单个表示下一个字符应指示要替换的数据类型。如果下一个字符是%,则它被解释为%字符,没有替换。
l='a'
r='%sbb%%'%l
print(r)
我期望输出abb%%,但实际输出是abb%。
谁能解释一下原因?
【问题讨论】:
% 用作字符串中替换的控制字符(例如 %s)时,您需要一种方法来处理实际 % 字符。单个表示下一个字符应指示要替换的数据类型。如果下一个字符是%,则它被解释为% 字符,没有替换。
百分号% 是一个特殊的元字符。我在下面描述了一些例子:
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 |
+------+----------------------------------------------+
【讨论】:
%%。 (仅仅添加一个%% 示例并没有帮助,因为问题已经有一个%% 示例。您需要实际解释一下。)