1

I am using python 3.5 and have a network address string like the following:

tcp://10.1.2.3:45678

I want to parse this string and extract the protocol, the ip address and the port number.

I know I can do this very easily with a string split or regex, however I was wondering if there is a python package or module that does this. I am sure that there is a specification for these string which defines them, hence I am interested in a python module instead of using regex or string parsing.

1 Answer 1

5

You are looking for urllib.parse.urlparse:

In [1050]: import urllib

In [1051]: urllib.parse.urlparse('tcp://10.1.2.3:45678')
Out[1051]: ParseResult(scheme='tcp', netloc='10.1.2.3:45678', path='', params='', query='', fragment='')

In [1052]: url = urllib.parse.urlparse('tcp://10.1.2.3:45678')

In [1053]: url.scheme
Out[1053]: 'tcp'

In [1054]: url.netloc
Out[1054]: '10.1.2.3:45678'

In [1055]: host, _, port = url.netloc.partition(':')

In [1056]: host
Out[1056]: '10.1.2.3'

In [1057]: port
Out[1057]: '45678'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you very much. This solution worked perfectly.
@ASaxena Glad I could help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.