仅使用 for 循环和 split 方法,我想计算名为 my_list 的字符串中有多少个 IP 地址

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

仅使用 for 循环和 split 方法,我想计算名为 my_list.

的字符串中有多少个 IP 地址
  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)

我觉得我错过了什么,但我想不通。感谢您的帮助

您可以简单地将字符串拆分为每个“inet”字并计算元素数。

计数减一,因为拆分将在第一次出现 "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)

运行时:

4

编辑:正如之前评论中提到的,它不是 list,而是 string。您的 for 循环遍历该字符串的每个字符。由于字符不能是 inet,条件总是 False 并且计数不会递增。

qkzk 发布的答案有效并且简单得多,但是发布这个是因为你想使用 for 循环。

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) 

输出

4

郑重声明,str 有一个 count 方法。

>>> 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