将字符串转换为元组

时间:2021-04-22 00:55:24

标签: python

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

1 个答案:

答案 0 :(得分:2)

正如@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 循环来实现,但它既乏味又耗时。

相关问题