Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 999
Zac Avatar asked Jan 03 '23 11:01

Zac


2 Answers

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.

like image 153
l'L'l Avatar answered Jan 15 '23 18:01

l'L'l


Try this

print('.'.join("192.168.0.50.XXXX".split('.')[:-1])) #or [:4], depending on what you want. To just remove the port, the -1 should work.
like image 36
whackamadoodle3000 Avatar answered Jan 15 '23 19:01

whackamadoodle3000