Search code examples
pythonpython-3.xstringlistlist-comprehension

Accessing index of a string within a comprehension


>> names = ["Cola", "Salah"]  
>> names1 = [s for s in names for i,c in enumerate(s)]
Output: "Cola","Cola","Cola","Cola","Salah","Salah","Salah","Salah","Salah",

I am trying to use python comprehension so that instead of outputting Cola and Salah 5 times, the output would be:

output: "Coolllaaaa", "Saalllaaaahhhhh"

I am wondering how would we access the index of the string. The code should be able to accept unicode.


Solution

  • Here is one approach using enumerate to loop over each index and character in a string element:

    >>> names = ["Cola", "Salah"]
    >>> [''.join([c * i for i, c in enumerate(s, 1)]) for s in names]
    ['Coolllaaaa', 'Saalllaaaahhhhh']
    

    This uses two list comprehensions, the first one to loop over each string in names, and the second one to loop over each character and index within the string, then multiply these values together and join them into a new string.