Search code examples
pythonreplacestrip

How do I strip combination of numbers and period in string in python?


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!


Solution

  • 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