简体   繁体   中英

Remove all caracters before a word in a Python list

I have a list of localizations but some of them won't work to get gps coordinates through an API, and I've found that it's only the ones with a "/" in them. I figured after trying on a single row that I need to remove the "/" and all characters before for it to work, but I can't seem to figure out how. This is what I've tried :

zones = [z.split(" /") for z in zones]

But it only returns all rows as "/". I can't use a lambda function since "zones" is a list.

Not exactly sure what you're after, but you can use re.sub to act on each string in the list. This will remove all characters in front of the first slash, including the slash.

import re

zones = ['aa  /jnjn', 'aaa/uhuhuhuhu', 'aaaaa  /plplplplpl']

zones = [re.sub(r'^.*?\/', '', z) for z in zones]
print(zones)

output:

['jnjn', 'uhuhuhuhu', 'plplplplpl']

You only need to split on the / ; the result is a list of strings, of which you want the last element. (With no / in the string, you'll get back a singleton element consisting of the original string, with no splitting performed.)

zones = [z.split("/", 1)[-1] for z in zones]

If there is only at most one / in a string, you can omit the second argument to split . With the second argument, it handles the more general case of removing everything up to and including the first / .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM