python正在搜索以开头的字符串

2024-10-06 14:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

data = cursor.fetchone ( )
while data is not None:
    data = str(data)
    print(data)
    data.split(",")
    for index in data:
        if index.startswith("K"):
            print(index, end=';')
    data = cursor.fetchone()

这是我代码的相关部分。数据是从mysql服务器检索的,是一个用逗号分隔的长文本字符串。我可以用逗号分隔字符串,但是,我需要搜索4个字母的字符串。我知道它们以K开头,但当我运行程序时,它只打印K。我如何让它打印整个字符串。
示例数据:
“N54,W130,克雷特,KMPI,咖啡”
预期输出:
“N54,W130,克雷特,KMPI,咖啡”
“克雷特;KMPI


Tags: 数据字符串dataindexisnotcursorprint
2条回答

如果您要查找以“K”开头的4个字母的字符串,那么使用正则表达式怎么样?在

import re

regex = r"K[a-zA-Z0-9]{3}"

test_str="N54,W130,KRET,KMPI,COFFEE"

matches = re.finditer(regex,test_str)

output=""
for matchNum, match in enumerate(matches):
    output+=match.group()+";"

print(output)

输出为:KRET;KMPI

您的行data.split(",")什么也不做,因为您需要分配该值。你还说你只想打印K?如果是这样,您只想打印字符串的第一个字符so d[0]

data = cursor.fetchone ( )
while data is not None:
    data = str(data)
    print(data)
    data = data.split(",")
    for d in data:
        if d.startswith("K"):
             print(d, end=';')
    data = cursor.fetchone()

编辑:根据你的编辑,你似乎想打印整个字符串,所以我更新了它

相关问题 更多 >