Defanging an IP Address

You can create a defanged version of a given IP address by replacing every period “.” with “[.]”. The Python code to achieve this is quite simple and straightforward:

1
2
3
class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace('.', '[.]')

Explanation

  • The replace method of a string replaces all occurrences of the first argument with the second argument.
  • In this case, it replaces every period “.” with “[.]”, and that’s exactly what we need to do to defang the IP address.

This solution is clear and concise and has a time complexity of O(n), where n is the length of the address.