将字符串转换为元组的函数

时间:2015-12-07 01:06:47

标签: python function python-3.x tuples

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

472747372 42 Lawyer John Legend Bishop

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

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

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

2 个答案:

答案 0 :(得分:0)

在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:])

这将允许您在姓氏

之后支持任意数量的“其他”名称

答案 1 :(得分:0)

怎么样:

$ ./bin/menuscan
Please enter a single word that is no more than 25 characters: 0123456789

Thanks! You entered:  0123456789

=========   MENU   =========

Key     Function
===     ========
 C      Count the letters
 V      Count the vowels
 R      Reverse the word
 P      Check if the word is a palindrome
 W      Enter a new word
 Z      Exit

Please enter a character from the options above: c

You entered: c


There are '10' letters in '0123456789'


=========   MENU   =========

Key     Function
===     ========
 C      Count the letters
 V      Count the vowels
 R      Reverse the word
 P      Check if the word is a palindrome
 W      Enter a new word
 Z      Exit

Please enter a character from the options above: z

You entered: z

或者:

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