如何在python中检查字符串是否为某种格式?

问题描述 投票:0回答:1

我将有一个字符串,我想检查它的格式为“float,float,float,float”。将会有3个逗号和4个浮点数,我不知道浮点数会有多少小数位。所以我想在不使用re class的情况下检查它。检查字符串后,我需要提取所有四个浮点数。所以在逗号前有3个浮点数,逗号后有1个浮点数。

我找不到一个字符串函数来做到这一点。我检查了我的python参考书,仍然找不到方法。我通常使用C ++编写代码,最近开始使用Python。谢谢您的帮助。

python-3.x
1个回答
1
投票

这是我对你的问题的尝试。

# Returns the list of four floating numbers if match and None otherwise
def four_float(str_input):
    # Split into individual floats
    lst = str_input.split(',')

    for flt in lst:
        # Check for the existence of a single dot
        d_parts = flt.strip().split('.')
        if len(d_parts) != 2:
            return None
        else:
            # Check that the chars on both sides of the dot are all digits
            for d in d_parts:
                if not d.isdigit():
                    return None

    return [float(n) for n in lst]
© www.soinside.com 2019 - 2024. All rights reserved.