Skip to content
Advertisement

how to show only the first letter of an element of a string [closed]

I have a list of words i.e. [‘cat’, ‘dog’, ‘chicken’] and I want to replace all letters except the first with an underscore. I tried using for loops but I couldn’t get it to work.

Advertisement

Answer

x = ['cat', 'dog', 'chicken']

y = [word[0] + '_'*(len(word)-1) for word in x]

print(y)
# ['c__', 'd__', 'c______']
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement