Search code examples
pythonstringpython-2.7tcpdump

Delete everything after 4th period in string


I'm trying to manipulate the output from tcpdump in python 2.7. What I'm trying to do is remove the port portion of the IP Address.

For example if the input string is

192.168.0.50.XXXX

How would I go about deleting everything after the 4th period so the output would be

192.168.0.50

I've thought about doing something with the length of the string the only thing is port lengths can be anywhere from 1-5 digits in my example(0-9999).

The only thing I can think of is doing something with the # of periods as a normal IP only contains 3 and an IP with Port attached has 4.


Solution

  • Use rsplit() for the cleanest or most simple route:

    s = "192.168.0.50.XXXX"
    s = s.rsplit('.',1)[0]
    

    Output:

    192.168.0.50
    

    rsplit()

    Returns a list of strings after breaking the given string from right side by the specified separator.