使用 python 字符串格式选项时标记“#”的功能是什么

what's the function of tag '#' while using python string format option

我正在使用 python 字符串格式选项,在阅读 document 之后,我仍然对 '#' 感到困惑,因为我真的不知道这个短语 '[=22] 的含义=]值转换将使用“替代形式”(定义如下)。'。非常感谢帮助我的人。

这是一些测试:

print '%#sabc' % 'ABC' 

'ABCabc'

print '%#fabc' % 1.2

1.200000abc

如果这里有一些使用“#”的例子就更好了。

根据该文档的注释,为某些转换类型定义了 'alternate form'。

例如在你的例子中 %#f

3.The alternate form causes the result to always contain a decimal point, even if no digits follow it.

没有为字符串定义 'Alternate form' 所以 %s%#s 是等价的

"alternative form" 稍微改变了所选转换的行为。

您的浮点表示示例:

'f': Floating point decimal format.

>>> print("%.0f" % 1)
1

The alternate form causes the result to always contain a decimal point, even if no digits follow it.

>>> print("%#.0f" % 1)
1.

十六进制表示示例:

'x': Signed hexadecimal (lowercase).

>>> print("%x" % -11)
-b

The alternate form causes a leading '0x' [...] to be inserted before the first digit.

>>> print("%#x" % -11)
-0xb