Defanging an IP Address in Python


Suppose we have a valid IPv4 IP address. We have to return the Defanged version of the IP address. A Defanged IP address is basically replace every period “.” by “[.]” So if the IP address is “192.168.4.1”, the output will be “192[.]168[.]4[.]1”

To solve this, we will follow these steps −

  • We will split the string using dot, then put each element separated by “[.]”

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def defangIPaddr(self, address):
      """
      :type address: str
      :rtype: str
      """
      address = address.split(".")
      return "[.]".join(address)

Input

"192.168.4.1"

Output

"192[.]168[.]4[.]1"
raja
Published on 16-Jan-2020 12:33:08
Advertisements