Home > Blockchain >  I'm trying to append a range of numbers onto a string in Python
I'm trying to append a range of numbers onto a string in Python

Time:05-04

The desired outcome I'm try to achieve is similar to this:

192.168.1.70    
192.168.1.71    
192.168.1.72    
192.168.1.73    
etc...

This is what I came up with but it isn't producing the desired outcome:

IP = "192.168.1."

for n in range(70,91):

    IP  = str(n)   "\n"

print(IP)

Instead it prints something like this:

192.168.1.70    
71    
72    
73    
etc...

Any help would be much appreciated. I'm totally lost.

CodePudding user response:

You can do it with a list comprehension:

[f"192.168.1.{i}" for i in range(70, 91)]

Output:

['192.168.1.70',
 '192.168.1.71',
 '192.168.1.72',
...

CodePudding user response:

You want to not use the same variable. Instead:

IP = "192.168.1."
IPout =""

for n in range(70,91):    
    IPout  = IP   str(n)   "\n"

print(IPout)

Essentially you want to concatenate to your IPout variable the IP plus the digits from the range().

CodePudding user response:

you will need to use a list to archive the values

ip = '192.168.1.'
ips = []
for i in range(70,91):
    ips.append(ip str(i)
print(ips)

CodePudding user response:

IP = "192.168.1."

Iprange=""

for n in range(70,91):

Iprange  = IP str(n)   "\n"

print(Iprange)

Try this lines. You have to assign range to another variable instead of same IP variable

  • Related