解析string类型的函数并返回值为int和str的元组

2024-04-23 13:44:41 发布

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

我无法理解这一点。字符串返回元组

我需要一个函数


def a (b):

to parse a string, lets say "35 age 6 ft" and parse it into a tuple of type(s) int, str, int string (35, "age", 6, "ft")

我不知道该怎么做。感谢您的帮助


Tags: andto函数字符串agestringparsedef
2条回答

要不依赖于输入大小,请使用列表理解并将结果列表转换为元组

def a(b):
    return tuple(int(x) if x.isdigit() else x for x in b.split(' '))

没有明确的解决方案来检查字符串是int还是float,因此您可以构建helper函数来检查它

def check_string(s):
    try:
        return int(s) # the value is int
    except ValueError:
        try:
            return float(s) # the value is float
        except ValueError:
            return s # the value is not a number

def a(b):
    return tuple(check_string(x) for x in b.split(' '))

您可以尝试以下方法:

def a(b):
    val = b.split()
    return (int(val[0]) if "." not in val[0] else float(val[0]), str(val[1]), int(val[2]) if "." not in val[2] else float(val[2]), str(val[3]))

res = a("35 age 6 ft")
print(res)

还有很多其他方法:-)

相关问题 更多 >