Check if string in the exact form of “,” in Python

前端 未结 1 371
感情败类
感情败类 2021-01-25 10:24

I\'m converting a string of two integers into a tuple. I need to make sure my string is formatted exactly in the form of \",\" with the comm

相关标签:
1条回答
  • 2021-01-25 10:57

    Sounds like a job for regular expressions.

    import re
    re.match("^\d+,\d+$", some_string)
    
    • ^ matches start of string
    • \d+ matches one or more digits
    • , matches comma literal
    • $ matches end of string

    Some testcases:

    assert re.match("^\d+,\d+$", "123,123")
    assert not re.match("^\d+,\d+$", "123,123 ")  # trailing whitespace
    assert not re.match("^\d+,\d+$", " 123,123")  # leading whitespace 
    assert not re.match("^\d+,\d+$", "a,b")  # not digits
    assert not re.match("^\d+,\d+$", "-1,3")  # minus sign is invalid
    

    Return value of re.match is either MatchObject or None, fortunately they behave as expected in boolean context - MatchObject is truthy and None is falsy, as can be seen is assert statements above.

    0 讨论(0)
提交回复
热议问题