Question on Joining of list

Terry Reedy tjreedy at udel.edu
Fri Jul 18 22:37:07 CEST 2008



SUBHABRATA wrote:
> Sorry if I didn't say that.
> The input is a string "Petrol Helium Heaven Sky"
> Now, in a3 it is "God Goddess Heaven Sky" is there,
 > ...I was looking for an output of  "H S Petrol Helium"

Meaningful names, splitting the target string, and using 'in' makes the 
code much easier.

inwords = "Petrol Helium Heaven Sky".split()
targets = "God Goddess Heaven Sky".split()
found = []
not_found = []

for word in inwords:
     if word in targets:
         found.append(word[0])
     else:
         not_found.append(word)

found.extend(not_found)
print(' '.join(found)) # 3.0

#prints the requested
H S Petrol Helium




More information about the Python-list mailing list