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

时间:2019-02-13 02:22:43

标签: python-3.x

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

我找不到执行此操作的字符串函数。我检查了我的python参考书,但仍然找不到方法。我通常用C ++编写代码,最近开始使用Python。谢谢您的帮助。

1 个答案:

答案 0 :(得分: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]