【问题标题】:Function to convert a string to a tuple将字符串转换为元组的函数
【发布时间】:2016-03-11 13:04:50
【问题描述】:

这是我将拥有哪些数据的示例:

472747372 42 Lawyer John Legend Bishop

我希望能够获取这样的字符串并使用函数将其转换为元组,以便将其拆分如下:

"472747372" "42" "Lawyer" "John Legend" "Bishop"

NI 号码、年龄、工作、姓氏和其他姓名

【问题讨论】:

  • String to list in Python的可能重复
  • “John Legend”和“Bishop”从何而来,您如何确定“John Legend”应该是单个字符串而不是拆分出来的?

标签: python function python-3.x tuples


【解决方案1】:

怎么样:

>>> string = "472747372 42 Lawyer John Legend Bishop"
>>> string.split()[:3] + [' '.join(string.split()[3:5])] + [string.split()[-1]]
['472747372', '42', 'Lawyer', 'John Legend', 'Bishop']

或者:

>>> string.split(maxsplit=3)[:-1] + string.split(maxsplit=3)[-1].rsplit(maxsplit=1)
['472747372', '42', 'Lawyer', 'John Legend', 'Bishop']

【讨论】:

  • 谢谢伙计。您能向我解释一下您键入的第二段代码是如何拆分字符串以使 John 和 Legend 在一起的吗?
【解决方案2】:

在 python 中,str 有一个名为split 的内置方法,它将字符串拆分为一个列表,根据您传递的任何字符进行拆分。默认是在空格上分割,所以你可以简单地做:

my_string = '472747372 42 Lawyer Hermin Shoop Tator'
tuple(my_string.split())

编辑:在 OP 更改帖子之后。

假设将总是有一个 NI 编号、年龄、工作和姓氏,您必须这样做:

elems = my_string.split()
tuple(elems[:3] + [' '.join(elems[3:5])] + elems[5:])

这将允许您在姓氏之后支持任意数量的“其他”名称

【讨论】:

  • 我认为'472747372', '42', 'Lawyer', 'Hermin', 'Shoop', 'Tator' != "472747372" "42" "Lawyer" "Hermin Shoop" "Tator"
  • 谢谢,但是我如何确保示例中的其他名称(例如“John”和“Legend”)放在一起。谢谢
  • "John""Legend" 不在输入中吗?
  • @Nlee57 更新了响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2016-03-14
  • 1970-01-01
  • 2012-01-19
相关资源
最近更新 更多