Removing characters from a string - Python

Asked

Viewed 222 times

1

Guys, I have the following problem.

I have a function that returns me the following output:

"Address:58.200.133.200"

I would like to save this value in a variable ip, but I only want the part of ip since output, so that it stays ip = "58.200.133.200".

I don’t have access to the function that generates this output, I just call it through an API.

3 answers

2


If your string always has this format, just take its suffix - because the prefix Address: (8 letters) is fixed:

s = "Address:58.200.133.200"
ip = s[8:]

If your input has any variance, the use of regular expressions may be more interesting, as pointed out in the Gypsy response.

1

I think it would be the case to use a regular expression:

import re
p = re.compile("Address:([\d\.]*)")
match = p.match(sua_string)
resultado = match.group()

1

If you do not use regex as the colleague explained, you can do:

>>> txt = "Address:58.200.133.200"
>>> txt.split(':')
['Address', '58.200.133.200']
>>> txt.split(':')[0]
'Address'
>>> txt.split(':')[1]
'58.200.133.200'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.