Search code examples
pythonpython-3.xip-address

How to print out a numbered IP Address in Python 3


Let say IP_Addresses is the variable for IP Addresses.

>>> IP_Addresses = '''
... 1.1.1.1
... 2.2.2.2
... 3.3.3.3
... '''
>>> 

If I use enumerate solution from this question, I did not get proper IP Adresss

How to print out a numbered list in Python 3

>>> for number, IP_Address in enumerate(IP_Addresses):
...     print(number, IP_Address)
... 
0 

1 1
2 .
3 1
4 .
5 1
6 .
7 1
8 

9 2
10 .
11 2
12 .
13 2
14 .
15 2
16 

17 3
18 .
19 3
20 .
21 3
22 .
23 3
24 

>>>

Desired Output

1 - 1.1.1.1
2 - 2.2.2.2
3 - 3.3.3.3

Solution

  • You could split the variable by newline, like so:

    IP_Addresses = '''
    ... 1.1.1.1
    ... 2.2.2.2
    ... 3.3.3.3
    ... '''
    
    i = 0
    IP_Addresses = IP_Addresses.split('\n')
    for line in IP_Addresses:
        if line and any(char.isdigit() for char in line):
            i += 1
            print(f'{i} - {line}')
    

    Output:

    1 - ... 1.1.1.1
    2 - ... 2.2.2.2
    3 - ... 3.3.3.3