Home > database >  Remove all caracters before a word in a Python list
Remove all caracters before a word in a Python list

Time:10-17

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.

CodePudding user response:

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']

CodePudding user response:

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

  • Related