Given a Python string like this:
location_in = 'London, Greater London, England, United Kingdom'
I would like to convert it into a list like this:
location_out = ['London, Greater London, England, United Kingdom',
                'Greater London, England, United Kingdom',
                'England, United Kingdom',
                'United Kingdom']
In other words, given a comma separated string (location_in), I would like to copy it to a list (location_out) and gradually break it down by removing the first word/phrase each time.
I'm a Python newbie. Any ideas on a good way to write this? Thanks.
location_in  = 'London, Greater London, England, United Kingdom'
locations    = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]
                        Here's a working one:
location_in = 'London, Greater London, England, United Kingdom'
loci = location_is.spilt(', ') # ['London', 'Greater London',..]
location_out = []
while loci:
  location_out.append(", ".join(loci))
  loci = loci[1:] # cut off the first element
# done
print location_out
                        Plenty of ways to do this, but here's one:
def splot(data):
  while True:
    yield data
    pre,sep,data=data.partition(', ')
    if not sep:  # no more parts
      return
location_in = 'London, Greater London, England, United Kingdom'
location_out = list(splot(location_in))
A more perverse solution:
def stringsplot(data):
  start=-2               # because the separator is 2 characters
  while start!=-1:       # while find did find
    start+=2             # skip the separator
    yield data[start:]
    start=data.find(', ',start)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With