How to make string check case insensitive?

前端 未结 4 558
难免孤独
难免孤独 2020-12-05 11:15

I\'ve started learning Python recently and as a practise I\'m working on a text-based adventure game. Right now the code is really ineffective as it checks the user responce

相关标签:
4条回答
  • 2020-12-05 11:36
    if 'power' in choice.lower():
    

    should do (assuming choice is a string). This will be true if choice contains the word power. If you want to check for equality, use == instead of in.

    Also, if you want to make sure that you match power only as a whole word (and not as a part of horsepower or powerhouse), then use regular expressions:

    import re
    if re.search(r'\bpower\b', choice, re.I):
    
    0 讨论(0)
  • 2020-12-05 11:36

    The str type/object has a method specifically intended for caseless comparison.

    At the python3 prompt:

    >>> help(str)
    ...
     |  casefold(...)
     |      S.casefold() -> str
     |      
     |      Return a version of S suitable for caseless comparisons.
    ...
    

    So, if you add .casefold() to the end of any string, it will give you all lowercase.

    Examples:

    >>> "Spam".casefold()
    'spam'
    >>> s = "EggS"
    >>> s.casefold()
    'eggs'
    >>> s == "eggs"
    False
    >>> s.casefold() == "eggs"
    True
    
    0 讨论(0)
  • 2020-12-05 11:48

    This if you're doing exact comparison.

    if choice.lower() == "power":
    

    Or this, if you're doing substring comparison.

    if "power" in choice.lower():
    

    You also have choice.lower().startswith( "power" ) if that interests you.

    0 讨论(0)
  • 2020-12-05 11:52

    use str.lower() to convert all entries to lowercase and only check the string against lower case possibilities.

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