Rob
Rob

Reputation: 3459

Collect position of characters in list of strings

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.

Upvotes: 0

Views: 52

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122042

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.

Upvotes: 4

Related Questions