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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With