首页 > 解决方案 > 字符串元素计数不起作用 [Python]

问题描述

我正在编写一个简单的服务器套接字接口(如控制台)。我试图实现一个SEND TO xxx.xxx.xxx.xxx命令来向 ip address 的客户端发送一些信息或命令xxx.xxx.xxx.xxx。所以我尝试编写这段代码(它在一个类中,这就是出现 self 参数的原因):

while True:
    # other statements

    # asking an input from the user
    command = input(f"[Server] >>> ")

    if command.startswith("SEND TO ") and \
        re.match(r"^([A-Z\s]){7}\s([0-9]{1,3}\.){3}([0-9]{1,3})$", command):

        # getting the ip address
        ip_address = command[8:]

        # ip lists (from self.__clients which is the list of connected 
        # clients)
        ip_list = [str(c.getpeername()[0]) for c in self.__clients]

        # count the occurrencies of the chosen ip (this because there can be 
        # multiple client connected from the same computer)
        matching_ip = ip_list.count(str(ip_address))

        # trying to print the results for debugging the code
        print(matching_ip)
        print(ip_list)
        print(ip_address)

这是控制台:

[Server] >>> SEND TO 111.111.1.11
0
['111.111.1.11', '111.111.1.11']
111.111.1.11

我无法弄清楚为什么即使有 2 次出现相同的 ip,匹配的 ip 变量仍保持值为 0。当我尝试从上一个输出中复制 ip(使用鼠标和CTRL+C)并粘贴(CTRL-V)到一个新行,使用它工作的相同SEND TO命令,并返回:

# where 111.111.1.11 is copied from the previous output (this works even if
# I copy 111.111.1.11 from a previous program run and i paste it for the
# first time in the current run)

[Server] >>> SEND TO 111.111.1.11
2
['111.111.1.11', '111.111.1.11']
111.111.1.11

有什么建议可以解决这个问题吗?

非常感谢您的时间,原谅我的英语,我还在练习

标签: pythonpython-3.xlistcount

解决方案


推荐阅读