python条带比要求的多

2024-03-28 22:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

'10000.0'.strip('.0')

应返回“10000”,但仅返回“1”。期望是错误的还是结果是错误的

如果字符串以“x.0”结尾,其中x不是0,则其行为正常。而且,对于任意x和任意n>;“[a-zA-Z0-9]x{n}.x{n}”,这个奇怪的结果是一致的;0 .

所以它所做的是,它不仅剥离了点后面的内容,而且也剥离了点之前的内容。如果这就是strip编程要做的,不知何故它与我的期望不符


Tags: 字符串gt内容编程错误结尾stripza
2条回答

这是根据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"匹配的所有字符

如果字符串中的字符与这些字符匹配,则会递归地将其删除。这就是为什么您将输出视为1

例如,11000.0的输出将是11

替代方案:替换?还是int()函数?

  1. int(float(10000.0))=10000

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

相关问题 更多 >