python strips 比要求的多

python strip strips more than asked for

'10000.0'.strip('.0')

预计 return '10000' 但 return 仅为 '1'。是期望错了还是结果错了?

如果字符串以 'x.0' 结尾,其中 x 不是 0,它会正常运行。此外,这个奇怪的结果对于 '[a-zA-Z0-9]x{n}.x 是一致的{n}' 对于任何 x 和任何 n>0 .

所以它所做的是,它不仅去除了点后面的内容,还去除了点之前的内容。如果这就是 strip 的编程目的,那么它与我的期望不符。

这是根据Docs

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

在这种情况下你最好使用round:

s='10000.0'
print(str(round(float(s))))

strip 函数没有按您预期的方式工作。

比如你的cmd是'10000.0'.strip('.0'):

这意味着,您要求它从匹配 "." or "0"

的字符串的 front/back 中删除所有字符

这会递归地从字符串中删除与这些字符匹配的字符。这就是为什么您看到输出为 1.

例如,11000.0 的输出将是 11

备选方案:替换?或 int() 函数?

  1. int(float(10000.0)) = 10000

  2. '10000.0'.replace('.0', '') = '10000'