3 回答

TA贡献1836条经验 获得超13个赞
一种方法是尝试转换您的输入并查看它是否可以管理。
编辑:这基本上是@martineau 在评论中建议的方法
以下代码改编自FlyingCircus(免责声明:我是主要作者):
def auto_convert(
text,
casts=(int, float, complex)):
"""
Convert value to numeric if possible, or strip delimiters from string.
Args:
text (str|int|float|complex): The text input string.
casts (Iterable[callable]): The cast conversion methods.
Returns:
val (int|float|complex): The numeric value of the string.
Examples:
>>> auto_convert('<100>', '<', '>')
100
>>> auto_convert('<100.0>', '<', '>')
100.0
>>> auto_convert('100.0+50j')
(100+50j)
>>> auto_convert('1e3')
1000.0
>>> auto_convert(1000)
1000
>>> auto_convert(1000.0)
1000.0
"""
if isinstance(text, str):
val = None
for cast in casts:
try:
val = cast(text)
except (TypeError, ValueError):
pass
else:
break
if val is None:
val = text
else:
val = text
return val
请注意,对于布尔情况,您需要一个专门的函数,因为bool(text)一旦text非空就会评估为 True (这也出现在最新版本的FlyingCircus as 中flyingcircus.util.to_bool())。

TA贡献1824条经验 获得超5个赞
好吧,您可以对输入运行正则表达式并检查哪个组不是None:
(?:^(?P<boolean>TRUE|FALSE)$)
|
(?:^(?P<integer>\d+)$)
|
(?:^(?P<float>\d+\.\d+)$)
|
(?:^(?P<string>.+)$)
在 regex101.com 上查看演示。首先,每个输入都是一个字符串。
在Python:
import re
strings = ["TRUE", "FALSE", "123", "1.234343", "some-string", "some string with numbers and FALSE and 1.23 in it"]
rx = re.compile(r'''
(?:^(?P<boolean>TRUE|FALSE)$)
|
(?:^(?P<integer>-?\d+)$)
|
(?:^(?P<float>-?\d+\.\d+)$)
|
(?:^(?P<string>.+)$)
''', re.VERBOSE)
for string in strings:
m = rx.search(string)
instance = [k for k,v in m.groupdict().items() if v is not None]
print(instance)
if instance:
print("{} is probably a(n) {}".format(string, instance[0]))
正如您在原始问题上方的评论中所说,您可能会遵循另一种方式try/except。

TA贡献1995条经验 获得超2个赞
例如,您可以使用以下代码围绕有效整数构建 if 语句: if isinstance(<var>, int):
否则获取类型type(<var>)
并围绕它构建函数。
添加回答
举报