尝试测试lis中的部分字符串

2024-09-29 17:15:38 发布

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

我有这样一个街区:

example of list:
pommes : 54
bananes : 18 : 99
orange 

你知道吗Ìt检验左字符串和右字符串是否用分隔,右字符串的类型是int

我想把多余的“:99”当作一个错误来抓。另外,ifmy:不存在。如果有任何方法可以将其添加到gauche2[2]

for i in message:
    parts = i.split(":")
    gauche = parts[0].strip()
    droite = parts[1]
    try:
        droite = int(droite)
        if not gauche.isalpha():
            print("La ligne '", i, "' n'est pas correctement formaté.")
            sys.exit()
    except ValueError:
        print("La ligne '", i, "' n'est pas correctement formaté.")
        sys.exit()  

Tags: 字符串formatexamplesysexitpaslaint
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:38

您可以使用split()len

data = """
exemple of list:
pommes : 54
bananes : 18 : 99
orange 
"""

for line in data.splitlines():
    if len(line.split(':')) > 2:
        raise ValueError(line, '<< bad line')

举个例子:

for i in message:
    parts = i.split(":")
    if len(parts) > 2:
        raise ValueError(i, '<< bad line')

相关问题 更多 >

    热门问题