Jonathan Ross
Jonathan Ross

Reputation: 33

Extract the first two characters of names in a list and concatenating into a string?

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

Answers (3)

Reut Sharabani
Reut Sharabani

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

RHSmith159
RHSmith159

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

Daniel Roseman
Daniel Roseman

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

Related Questions