KRL
KRL

Reputation: 195

How to extract a part of a list of strings?

I have a list of strings and I want to extract the first 6 characters of each string and store them in a new list.

I can loop through the list and extract the first 6 characters and append them to a new list.

y = []
for i in range(len(x)):
    y.append(int(x[i][0:6]))

I want to know if there is an elegant one line solution for that. I tried the following:

y = x[:][0:6]

But it returns a list of the first 6 strings.

Upvotes: 6

Views: 33711

Answers (5)

prashant
prashant

Reputation: 3318

Try this

ans_list = [ element[:6] for element in list_x ]

Upvotes: 2

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

You can also use map for this:

list(map(lambda w: int(w[:6]), x))

and using itertools.islice:

list(map(lambda w:list(int(itertools.islice(w, 6))), x))

Upvotes: 0

Feelsbadman
Feelsbadman

Reputation: 1165

Yes, there is. You can use the following list-comprehention.
newArray = [x[:6] for x in y]

Slicing has the following syntax: list[start:end:step]

Arguments:

start - starting integer where the slicing of the object starts
stop - integer until which the slicing takes place. The slicing stops at index stop - 1.
step - integer value which determines the increment between each index for slicing


Examples:


    list[start:end] # get items from start to end-1
    list[start:]    # get items from start to the rest of the list
    list[:end]      # get items from the beginning to the end-1 ( WHAT YOU WANT )
    list[:]         # get a copy of the original list

if the start or end is -negative, it will count from the end


    list[-1]    # last item
    list[-2:]   # last two items
    list[:-2]   # everything except the last two items
    list[::-1]  # REVERSE the list

Demo:
let's say I have an array = ["doctorWho","Daleks","Cyborgs","Tardis","SonicSqrewDriver"]

and I want to get the first 3 items.

>>> array[:3] # 0, 1, 2 (.. then it stops)
['doctorWho', 'Daleks', 'Cyborgs']

(or I decided to reverse it):

>>> array[::-1]
['SonicSqrewDriver', 'Tardis', 'Cyborgs', 'Daleks', 'doctorWho']

(now i'd like to get the last item)

>>> array[-1]
'SonicSqrewDriver'

(or last 3 items)

>>> array[-3:]
['Cyborgs', 'Tardis', 'SonicSqrewDriver']

Upvotes: 4

Gokul
Gokul

Reputation: 39

This might help

stringList = ['abcdeffadsff', 'afdfsdfdsfsdf', 'fdsfdsfsdf', 'gfhthtgffgf']
newList = [string[:6] for string in stringList]

Upvotes: 2

GeeTransit
GeeTransit

Reputation: 1468

Try this:

y = [z[:6] for z in x]

This was the same as this:

y = []               # make the list
for z in x:          # loop through the list
    y.append(z[:6])  # add the first 6 letters of the string to y

Upvotes: 9

Related Questions