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?

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
Michal
  • 3,496
  • 7
  • 44
  • 70

3 Answers3

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.

thefourtheye
  • 221,210
  • 51
  • 432
  • 478
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
vaultah
  • 40,483
  • 12
  • 109
  • 137
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]))
user189
  • 604
  • 3
  • 11