首页 > 解决方案 > 将字符串转换为元组

问题描述

给定一个字符串“key:content”,我想返回一个元组(key,content),
我找到了一些神秘的方法来做到这一点。有没有一种简单的方法可以在 python 中做到这一点

标签: 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循环来实现,但是比较繁琐且耗时。


推荐阅读