Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
For example:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"
Write a function that takes a string representing a valid IPv4 address and returns a new string with all periods replaced by [.]
.
def defang_ip_address(address: str) -> str:
"""Defangs an IPv4 address by replacing each period "." with "[.]".
Args:
address (str): A valid IPv4 address.
Returns:
str: The defanged IP address.
"""
return address.replace(".", "[.]")
# Example usage:
address1 = "1.1.1.1"
defanged_address1 = defang_ip_address(address1)
print(f"Original address: {address1}, Defanged address: {defanged_address1}")
address2 = "255.100.50.0"
defanged_address2 = defang_ip_address(address2)
print(f"Original address: {address2}, Defanged address: {defanged_address2}")
The replace()
method in Python has a time complexity of O(n), where n is the length of the input string. In this case, the length of the IP address string is relatively small (typically 15 characters for IPv4). Therefore, the run-time complexity can be considered O(1), assuming the length of the IP address is constant.
The replace()
method creates a new string. In the worst-case scenario, every character in the original string needs to be replaced. The new string will have the same number of characters as the original. The space required for the new string is O(n). Again, since the length of IP address is relatively small, the space usage can be considered O(1).
Invalid IP Address Format:
Empty String:
String with No Periods:
Leading/Trailing Spaces: