Reputation: 181
I have a column with strings that look like below. They are combination of IP Address and system name. I want to strip the IP address part of the string, which is everything before the first hyphen.
str = "12.345.678.9-abcd1_0-def-ghi-4567"
So far, I've tried below,
str.replace('\D+', '')
str.lstrip('\D+', '')
str.rstrip('\D+', '')
'I want to delete everything until the first hyphen.' This sounds like a simple task but I'm experiencing a learning curve. Please help!
Upvotes: 1
Views: 922
Reputation: 38415
Try this: import re m = re.search('\d+-(.*)', s).group(1)
You get 'abcd1_0-def-ghi-4567'
Upvotes: 0
Reputation: 57033
A regex-based solution to the collection:
re.findall(r'[^-]+-(.+)',s)[0]
#'abcd1_0-def-ghi-4567'
Upvotes: 0
Reputation: 577
You can find()
the first '-'
and then take a slice from that point on:
>>> s = '12.345.678.9-abcd1_0-def-ghi-4567'
>>> s[s.find('-')+1:]
'abcd1_0-def-ghi-4567'
Upvotes: 0
Reputation: 127
If all your strings are formatted in that same way, you could just split the string on the hyphen using the str.split()
method, remove the first item of the resulting list, and then use the str.join()
method to combine it again like so:
string = "12.345.678.9-abcd1_0-def-ghi-4567".split("-")[1:]
>>> ['abcd1_0', 'def', 'ghi', '4567']
joined_str = "-".join(string)
>>> abcd1_0-def-ghi-4567
Upvotes: 1