Search code examples
pythonpython-3.xstringpython-restartswith

Trying to check a string with startswith


I'm trying to use startswith to check if something begins with this symbol '<' and then alphanumerical characters. My code is:

if (line.startswith("<" + r"w\+")):

I was expecting that if line started with <inserttexthere> or <inserttexthere it would output True but it's not working. It's probably something to do with my use of re and that I didn't format the check for alphanum characters properly.


Solution

  • It's because you doesn't use regex. line.startswith("<" + r"w\+") means check if regex start with string "<w\\+" exact value not regex interpretation.

    In addition startswith doesn't allow regex so you should check it this way:

    import re
    
    # Edit as @donkopotamus pointed well that match doesn't require '^' at the begining
    in_re = re.compile(r'<\w+')
    
    print(bool(in_re.match('<test true')))
    print(bool(in_re.match('test false')))
    print(bool(in_re.match('test <false 2')))
    

    It returns:

    True
    False
    False