1

Here is an example of what data I will have:

472747372 42 Lawyer John Legend Bishop

I want to be able to take a string like that and using a function convert it into a tuple so that it will be split like so:

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

NI Number, Age, Job, surname and other names

NLee57
  • 71
  • 1
  • 9
  • 3
    Possible duplicate of [String to list in Python](http://stackoverflow.com/questions/5453026/string-to-list-in-python) – 101 Dec 07 '15 at 01:07
  • 1
    Where did "John Legend" and "Bishop" come from and how do you determine "John Legend" should be a single string instead of split out? – Colin Dec 07 '15 at 01:09

2 Answers2

0

In python, str has a built-in method called split which will split the string into a list, splitting on whatever character you pass it. It's default is to split on whitespace, so you can simply do:

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

EDIT: After OP changed the post.

Assuming there will always be an NI Number, Age, Job, and surname, you would have to do:

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

This will allow you to support an arbitrary number of "other" names after the surname

dursk
  • 4,435
  • 2
  • 19
  • 30
0

What about:

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

Or:

>>> string.split(maxsplit=3)[:-1] + string.split(maxsplit=3)[-1].rsplit(maxsplit=1)
['472747372', '42', 'Lawyer', 'John Legend', 'Bishop']
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • Thanks man. Can you explain to me how the second piece of code you typed splits the string so that John and Legend are together? – NLee57 Dec 07 '15 at 01:43