python - 将字符串转换为元组
问题描述
给定一个字符串“key:content”,我想返回一个元组(key,content),
我找到了一些神秘的方法来做到这一点。有没有一种简单的方法可以在 python 中做到这一点
解决方案
正如@ShadowRanger 建议的那样,使用该tuple()
函数是转换为 tulpe 的最简单方法之一。我们使用string.split()
函数将字符串分成两部分。
因此,我们以这种方式实现它:
string = "key: content" # given string
mytuple = tuple(string.split(": ")) # split the string from ": " and convert it into a tuple
print(mytuple)
>>> ("key", "content")
注意:这也可以通过使用for
循环来实现,但是比较繁琐且耗时。
推荐阅读
- vue.js - 在 vue js 的 main.js 中使用 async api
- java - 如何频繁替换整个 SQL 表数据?
- powershell - 以 SQL 阅读器的 ArrayList 中的额外空值结束
- java - 是否可以在 javaFx 标签中显示字符串格式的表格?
- javascript - 将数据表与 JSP 一起使用不会返回表中的查询数据并向我发送错误
- angular - 变更检测器正在等待完成 API 服务调用
- python - 在 Linux 服务器中使用 Digital Persona DLL 库
- javascript - 调用不带括号的 JS 函数
- c# - 如何在unity3d中更改碰撞时的立方体宽度
- encryption - 如何加密 Kubernetes 环境中容器使用的实际存储/卷?