0

If I have a list of strings and I want to gather the position of each character in the string, what would be the best way? For example, if I had a list:

text = []
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text.append(line)

text = ['fda', 'adf', 'esf', 'esfe']

and I wanted to create something like:

 newlst = ['faee', 'ddss', 'afff', 'e']

Is there a simple way? I'm creating multitudes of for loops and it seems convoluted.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Rob
  • 3,333
  • 5
  • 28
  • 71

1 Answers1

4

You can use izip_longest from itertools*:

>>> from itertools import izip_longest
>>> text = ['fda', 'adf', 'esf', 'esfe']
>>> map(''.join, izip_longest(*text, fillvalue=''))
['faee', 'ddss', 'afff', 'e']

This creates an iterator of tuples of the characters at each position:

>>> list(izip_longest(*text, fillvalue=''))
[('f', 'a', 'e', 'e'), ('d', 'd', 's', 's'), ('a', 'f', 'f', 'f'), ('', '', '', 'e')]

Then uses map and str.join to convert the tuples back into strings. If the * syntax is unfamiliar, see What does ** (double star) and * (star) do for parameters?


* If using Python 3.x, note that this function has been renamed to zip_longest, as zip now takes the iterator behaviour and izip no longer exists - see e.g. What's New in Python 3.0.

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437