Reputation: 33
I have a list
names = ['John', 'Ralph', 'Frank', 'Luke', 'David', 'Helen', 'Chloe', 'Sophia']
I want to take the first two letters and combine them together such as:
JoRaFrLuDaHeChSo
I found the code below that does a similar job and I added [:2] to get the first two letters however it doesn't work.
print("".join([str(x) for x in names[:2]))
Upvotes: 1
Views: 1298
Reputation: 31339
You can also qvoid syntax if you like:
names = ['John', 'Ralph', 'Frank', 'Luke', 'David', 'Helen', 'Chloe', 'Sophia']
# import the needed standard functions
from itertools import islice, repeat, chain
# take 2 initial characters of each string
prefixes = map(islice, names, repeat(2))
# chain prefixes
concatenated = chain.from_iterable(prefixes)
# join to one string
result = ''.join(concatenated)
Upvotes: 0
Reputation: 1592
You were almost there, the list slicing needs to be done on the string, not the original list.
my_string = "".join([x[:2] for x in names])
Upvotes: 2
Reputation: 599610
You put the slice in the wrong place. Also, the names are already strings, you don't need str()
.
print("".join([x[:2] for x in names]))
Upvotes: 4