1108. Defanging an IP Address

1108. Defanging an IP Address

题目

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

Example 1:

1
2
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2:

1
2
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

Constraints:

  • The given address is a valid IPv4 address.

解题

很简单的一道题,字符串的替换。

第一次尝试:最开始没有想起replace方法,用了笨办法(split方法)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
new_ip = ''
numbers = address.split('.')
for number in numbers:
if number != '.':
new_ip += number + '[.]'
return new_ip[:-3]

更好的答案:

1
2
3
4
5
6
7
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
return address.replace('.', '[.]')

总结

  1. 这里弄混了split和strip方法,特此总结:

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

1
str.strip([chars])

Python split() 通过指定分隔符对字符串进行切片,如果参数num有指定值,则分隔num+1个子字符串(num表示分割次数)

1
str.split(str="", num=string.count(str))

这里也可以用split方法与str.join(sequence)方法拼接获得结果。

  1. 任何可以用 for 循环c遍历的东西都是可迭代的。python的字符串也是可迭代的。所以有:
1
2
3
str = '1.1.1.1'
for a in str:
print(a)

结果为:

1
2
3
4
5
6
7
1
.
1
.
1
.
1
  1. 每一种语言都有相应的字符串替换函数,如:

C++中可以用regex_replace(address, regex("[.]"), "[.]");

JAVA中可以用address.replace(".", "[.]");或者String.join("[.]", address.split("\\."));