Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 345
KRL Avatar asked Jan 06 '19 04:01

KRL


2 Answers

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
like image 98
GeeTransit Avatar answered Oct 14 '22 18:10

GeeTransit


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']
like image 23
Feelsbadman Avatar answered Oct 14 '22 18:10

Feelsbadman