Python拆分、替换

use*_*554 3 python

我正在写一份便条,但遇到了障碍。可能有一种更有效的方法来做到这一点,但我对 Python 相当陌生。我正在尝试创建用户生成的 IP 地址列表。我正在使用 print 来查看生成的值是否正确。当我运行此代码时,打印 ip_start 具有相同的值并且未更新。我确信这是一个相当简单的修复,但我有一个主要的脑锁。

ip_start = raw_input('Please provide the starting IP address for your scan --> ')
start_list = ip_start.split(".")
ip_end = raw_input('Please provide the ending IP address for your scan --> ')
end_list = ip_end.split(".")
top = int(start_list[3])
bot = int(end_list[3])
octet_range = range(top,bot)
print octet_range
for i in octet_range:
    print i
    print "This the top:" + str(top)
    ip_start.replace(str(top),str(i))
    print ip_start
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 8

字符串上的方法replace不会就地修改字符串。事实上,没有任何东西会就地修改字符串;它们是一成不变的教程“字符串”部分对此进行了解释。

它的作用是返回一个新字符串,并对其进行替换。来自文档

strreplace(,[,计数])

返回字符串的副本,其中所有出现的子字符串old都替换为new。如果给出了可选参数count ,则仅替换第一个出现的count 。

所以,你想要的是:

ip_start = ip_start.replace(str(top),str(i))
Run Code Online (Sandbox Code Playgroud)