python - 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)的方式来归档它?
解决方案
您可以使用正则表达式来
- 检查给定值是否有效
- 检索要转换的值和转换方式
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
推荐阅读
- c# - 在 C# 中是否可以从子类继承子类?
- firebase - 如何使用 Firestore 查询我关注的用户最近提交的内容?
- jenkins - 如何在詹金斯控制台的一个步骤中输出动态更新的变量。我为工作传递的配置文件(环境文件)
- javascript - 如何创建数量可变的 Stripe 订阅?
- r - 如何在 ggplot2 图中修改和添加额外的图例
- android - 不应该将 .class.getSimpleName() 用于标签吗?
- css - 当父级具有相对定位时,悬停菜单的最大宽度被忽略
- ssl-certificate - 无法使用新的 puppet master 生成新的 puppet 证书
- php - $_SESSION 消息在 header() 发送后被取消设置
- windows - 如何在 Jupyter 笔记本中包含 Julia 文件?