Slice all strings in a list?

家住魔仙堡 提交于 2020-05-13 06:17:07

问题


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).


回答1:


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]


来源:https://stackoverflow.com/questions/39908314/slice-all-strings-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!