我不明白为什么第二个版本有效。在代码的第一段中,输出为"1.1.1.1"
,在代码的第二段中,输出为1[.]1[.]1[.]1
,这是怎么回事?为什么第一段不打印出与第二段相同的内容?
我尝试了一切
class Solution:
def defangIPaddr(self, address: str) -> str:
'''
takes in a str variable called address
returns a string
'''
address.replace('.','[.]')
return address
class Solution:
def defangIPaddr(self, address: str) -> str:
'''
takes in a str variable called address
returns a string
'''
return address.replace('.','[.]')
我希望第一版代码功能的输出为1[.]1[.]1[.]1
。
答案 0 :(得分:1)
在Python(和许多其他编程语言)中,字符串是不可变 。这意味着您不能更改字符串的内容,只能创建一个新字符串,该字符串是原始字符串的修改后的副本。
因此,这意味着address.replace('.','[.]')
不会不更改address
字符串,它会创建一个 new 字符串,该字符串将由该方法返回。但是在您的第一个函数中,您忽略了该结果。因此,这意味着您只需返回原始字符串即可。
通过使用return address.replace('.','[.]')
,您将返回该函数调用的结果,即与原始字符串相比,其中.
被[.]
替换的字符串。