Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a symbol between every letter in a list of strings

Tags:

python

How would I put ! after every character in a list

listOne = ["hello","world"]

How do I turn that into:

["h!e!l!l!o","w!o!r!l!d"]

Attempt:

def turn(List):
    return [i for i in (list(lambda x: "%s!" % x,listOne))]
turn(listOne)

Returns:

['hello!',"world!"]

Is their another way to do this besides:

def turn(List):
    x = ""
    for word in words:
        for letter in word:
            x += "%s!" % letter
    return x
turn(listOne)

I'm not a big fan of doing things like that however I do realize that may be more pythonic than what I'm trying to do which is make it as few lines as possible so. Is this possible?

like image 491
ruler Avatar asked Dec 12 '22 10:12

ruler


1 Answers

You can easily achieve this with the str.join() method, and list comprehension:

>>> listOne = ['!'.join(i) for i in listOne]
>>> listOne

Output

['h!e!l!l!o', 'w!o!r!l!d']

Alternatively, as abarnert suggested, you can use the bulit-in map function.

>>> listOne = list(map('!'.join, listOne))
>>> listOne
['h!e!l!l!o', 'w!o!r!l!d']

Hope this helps!

like image 85
aIKid Avatar answered Jan 03 '23 00:01

aIKid