Search code examples
pythoncase-insensitive

String comparison in Python that is case-insensitive for first letter


I need to match the following string File system full. The problem is Starting F can be lowercase or capital. How can I do this in Python when string comparisons are usually case-sensitive?


Solution

  • I'll be providing boolean indicators for you to play around with (rather than actual if blocks for the sake of conciseness.

    Using Regex:

    import re
    bool(re.match('[F|f]',<your string>)) #if it matched, then it's true.  Else, false.
    

    if the string could be anywhere in your output (I assume string)

    import re
    bool(re.search('[F|f]ile system full',<your string>))
    

    Other options:

    checking for 'f' and 'F'

    <your string>[0] in ('f','F')
    
    <your string>.startswith('f') or <your string>.startswith('F')
    

    And there's the previously suggested lower method:

    <your string>.lower() == 'f'