首页 > 解决方案 > Python:拆分字符串并转换为其他类型

问题描述

我有一个函数可以得到这样格式的字符串:

"true"^^<http://www.w3.org/2001/XMLSchema#boolean>
"100"^^<http://www.w3.org/2001/XMLSchema#int>

现在我想在字符上拆分字符串^^并根据第二部分转换字符串的第一部分。我还想"在转换之前删除第一个。

这是我用于此的代码:

def getValue(tObject):
    toReturn = tObject.split("^^")
    if len(toReturn) == 2:
        if toReturn[1] == "<http://www.w3.org/2001/XMLSchema#boolean>":
            return bool(toReturn[0].replace('"', ""))
        elif toReturn[1] == "<http://www.w3.org/2001/XMLSchema#int>":
            return int(toReturn[0].replace('"', ""))
    return None

但我对此并不满意。是否有更优雅(pythonic)的方式来归档它?

标签: pythonpython-3.xstring

解决方案


您可以使用正则表达式来

  • 检查给定值是否有效
  • 检索要转换的值和转换方式
PATTERN = re.compile(r'"(.*)"\^\^<http:.*#(\w+)>')
types = {"boolean": bool, "int": int}

def getValue(value):
    m = PATTERN.fullmatch(value)
    return types[m.group(2)](m.group(1)) if m else None

推荐阅读