Home > Net >  using the for loop and the split method only, I want to count how many IP address there is on the st
using the for loop and the split method only, I want to count how many IP address there is on the st

Time:01-08

using the for loop and the split method only, I want to count how many IP address there is on the string called my_list.

  my_list = \
  '''
  inet addr :127.0.0.1 Mask:255.0.0.0
  inet addr :127.0.0.2 Mask:255.0.0.0

  inet addr :127.0.0.3 Mask:255.0.0.0
  inet addr :127.0.0.4 Mask:255.0.0.0
  '''

  count = 0
  for i in my_list : #this is the for loop but it returns 0 instead of 4
     if i == "127" :
       count = count   1
  print(count)

I feel like I am missing something but I can't figure it out. Thank you for any help

CodePudding user response:

Just for the record, str has a count method.

>>> my_list = \
...   '''
...   inet addr :127.0.0.1 Mask:255.0.0.0
...   inet addr :127.0.0.2 Mask:255.0.0.0
... 
...   inet addr :127.0.0.3 Mask:255.0.0.0
...   inet addr :127.0.0.4 Mask:255.0.0.0
...   '''
>>> my_list.count('inet')
4

CodePudding user response:

The answer posted by qkzk works and is much simpler, but posting this because you want to use for loop.

my_list = \
  '''
  inet addr :127.0.0.1 Mask:255.0.0.0
  inet addr :127.0.0.2 Mask:255.0.0.0

  inet addr :127.0.0.3 Mask:255.0.0.0
  inet addr :127.0.0.4 Mask:255.0.0.0
  '''

# split the string at each end of line to convert it to a list of string
my_list_of_strings = my_list.split('\n')


count = 0
for string in my_list_of_strings: 
    if "127" in string : # check if '127' is in string 
        count = count   1

print(count) 

Output

4

CodePudding user response:

You can simply split the string every "inet" word and count the elements.

The count is off by one since split will create an empty string before the first occurrence of "inet"

my_string = """ inet addr :127.0.0.1 Mask:255.0.0.0 inet addr :127.0.0.2 Mask:255.0.0.0 inet addr :127.0.0.3 Mask:255.0.0.0 inet addr :127.0.0.4 Mask:255.0.0.0 
"""


count = len(my_string.strip().split("inet")) - 1

print(count)

When runned :

4

edit: as mentioned in previous comment, it's not a list but a string. Your for loop iterates over every character of that string. Since a character can't be inet, the condition is always False and the count isn't incremented.

  •  Tags:  
  • Related