how do I remove all occurrences in a string up to the first space, so that:
strings = ["1234 zoocore", "4356 00's punk"]
becomes: ["zoocore", "00's punk"]
?
I have tried regex:
for s in strings:
new_s = re.sub(r'\d+','', s)
but that erases 00'
as well, which I don't want.
You can use str.split
with maxsplit
parameter:
>>> strings = ["1234 zoocore", "4356 00's punk"]
>>> [s.split(None, 1)[1] for s in strings]
['zoocore', "00's punk"]
If you have strings that don't contain space you can use -1
as index:
>>> strings = ["1234 zoocore", "4356 00's punk", "rock"]
>>> [s.split(None, 1)[-1] for s in strings]
['zoocore', "00's punk", 'rock']
Your mistake is that you didn't anchor the match at the start of the string and that you didn't include the space. Here's a fixed version:
>>> [re.sub(r'^\d* ', '', s) for s in strings]
['zoocore', "00's punk"]
And just another way, finding the space (if any) and then slicing the string.
>>> strings = ["1234 zoocore", "4356 00's punk", "rock"]
>>> [s[s.find(' ') + 1:] for s in strings]
['zoocore', "00's punk", 'rock']
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.