3

I am using Python 3.3. I have this string:

"Att education is secondary,primary,unknown"

now I need split the last three words (there may be more or only one) and create all possible combinations and save it to list. Like here:

"Att education is secondary"
"Att education is primary"
"Att education is unknown"

What is the easiest way to do it?

3 Answers 3

3
data = "Att education is secondary,primary,unknown"
first, _, last = data.rpartition(" ")
for item in last.split(","):
    print("{} {}".format(first, item))

Output

Att education is secondary
Att education is primary
Att education is unknown

If you want the strings in a list, then use the same in list comprehension, like this

["{} {}".format(first, item) for item in last.split(",")]

Note: This may not work if there are spaces in the middle of the comma separated values or in the values themselves.

Sign up to request clarification or add additional context in comments.

Comments

3
a = "Att education is secondary,primary,unknown"
last = a.rsplit(maxsplit=1)[-1]
chopped = a[:-len(last)]

for x in last.split(','):
    print('{}{}'.format(chopped, x))

If you can guarantee that you words are delimited with a single space this will also work (more elegant):

chopped, last = "Att education is secondary,primary,unknown".rsplit(maxsplit=1)
for x in last.split(','):
    print('{} {}'.format(chopped, x))

Will work fine as long as the last words' separator doesn't include whitespace.

Output:

Att education is secondary
Att education is primary
Att education is unknown

2 Comments

Little inefficient, you might want to do a.rsplit(" ", 1)
Thanks, Can you please explain how is split better than rsplit with maxsplit set to 1?
2
s="Att education is secondary,primary,unknown".split()

w=s[1]
l=s[-1].split(',')

for adj in l:
    print(' '.join([s[0],w,s[2],adj]))

Comments

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.