【发布时间】:2021-11-15 11:42:47
【问题描述】:
假设如下:
>>> square = '²' # Superscript Two (Unicode U+00B2)
>>> cube = '³' # Superscript Three (Unicode U+00B3)
奇怪的是:
>>> square.isdigit()
True
>>> cube.isdigit()
True
好的,让我们将这些“数字”转换为整数:
>>> int(square)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '²'
>>> int(cube)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '³'
哎呀!
有人能解释一下我在处理字符串时应该从str.isdigit() 方法中得到什么行为吗?
【问题讨论】:
-
我会投票关闭它作为How can I check if a string represents an int, without using try/except? 的副本,如果这没有特别询问避免尝试/除外(投票最多的答案只是
isdigit,第二个-从上到下是你想要的)。也相关:What's the difference between str.isdigit, isnumeric and isdecimal in Python? -
您是想检查字符串是否可以转换为整数,还是只是想了解
isdigit的作用?如果您试图回答后者,文档将是第一个转向的地方。
标签: python python-3.x