0

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 ;)

1
  • 2
    How would you go about it, and in what way(s) does it not work? Commented Jul 23, 2016 at 22:02

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

6 Comments

Hi thanks for your help, I tried implementing the first method however it did not work when used in a function like the following: (where 'x' is a string) def strTup(x): payR, dep, sal, *other, surn = x.split() payR, dep, sal, " ".join(other), surn
Sorry for the layout of the code, Its not easy in comments lol, please could you tell me how to get this working so that it returns a tuple like in the above example, thanks :)
Well,you have to return the tuple; in my code I just echoed it in the interactive shell. In your function, use return payR, dep, sal, " ".join(other), surn.
I was having some trouble implementing it and getting it to return the output when ran, however I have sorted that now
@RJB Good to hear that. Just drop a comment if you have any more troubles.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.