Reputation: 447
I am writing a scrip and have run into a roadblock. There is probably a more efficient way to do this, but I am fairly new to Python. I am trying to create a list of user generated IP addresses. I am using print to see if the produced values are correct. When I run this code, the print ip_start has the same value and is not updated. I am sure this is a fairly simple fix but I have a major brain lock.
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
Upvotes: 3
Views: 17701
Reputation: 57630
ip_start.replace(...)
— just like every other str
method — does not modify ip_start
. Instead, it returns a modified string which you must then assign to ip_start
if you want to change it.
Upvotes: 1
Reputation: 366083
The replace
method on strings doesn't modify the strings in-place. In fact, nothing modifies strings in-place; they're immutable. This is explained in the Tutorial section Strings.
What it does is return a new string with the replacements done on it. From the docs:
str
.replace
(old, new[, count])Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
So, what you want is:
ip_start = ip_start.replace(str(top),str(i))
Upvotes: 8