RonB7
RonB7

Reputation: 297

Python Multiple Strings to Tuples

Hi everyone I wonder if you can help with my problem.

I am defining a function which takes a string and converts it into 5 items in a tuple. The function will be required to take a number of strings, in which some of the items will vary in length. How would I go about doing this as using the indexes of the string does not work for every string.

As an example -

I want to convert a string like the following:

Doctor E212 40000 Peter David Jones

The tuple items of the string will be:

Job(Doctor), Department(E212), Pay(40000), Other names (Peter David), Surname (Jones)

However some of the strings have 2 other names where others will have just 1.

How would I go about converting strings like this into tuples when the other names can vary between 1 and 2?

I am a bit of a novice when it comes to python as you can probably tell ;)

Upvotes: 0

Views: 494

Answers (1)

tobias_k
tobias_k

Reputation: 82929

With Python 3, you can just split() and use "catch-all" tuple unpacking with *:

>>> string = "Doctor E212 40000 Peter David Jones"
>>> job, dep, sal, *other, names = string.split()
>>> job, dep, sal, " ".join(other), names
('Doctor', 'E212', '40000', 'Peter David', 'Jones')

Alternatively, you can use regular expressions, e.g. something like this:

>>> m = re.match(r"(\w+) (\w+) (\d+) ([\w\s]+) (\w+)", string)
>>> job, dep, sal, other, names = m.groups()
>>> job, dep, sal, other, names
('Doctor', 'E212', '40000', 'Peter David', 'Jones')

Upvotes: 4

Related Questions