Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice all strings in a list?

Is there a Pythonic way to slice all strings in a list?

Suppose I have a list of strings:

list = ['foo', 'bar', 'baz']

And I want just the last 2 characters from each string:

list2 = ['oo', 'ar', 'az']

How can I get that?

I know I can iterate thru the list and take list[i][-2:] from each one, but that doesn't seem very Pythonic.

Less generally, my code is:

def parseIt(filename):
    with open(filename) as f:
        lines = f.readlines()

   result = [i.split(',') for i in lines[]]

...except I only want to split lines[i][20:] from each line (not the whole line).

like image 219
nerdfever.com Avatar asked Mar 11 '23 23:03

nerdfever.com


1 Answers

You mentioned that you can do list[i][-2:] for transforming the list per your specification, but what you are actually looking for is:

[word[1:] for word in lst]

Furthermore, for the code sample you provided where you are looking to slice 20 characters from the beginning, the solution would be the same:

result = [i[20:].split(',') for i in lines]
like image 65
idjaw Avatar answered Mar 20 '23 13:03

idjaw