Python - How to make user input not case sensitive?

后端 未结 3 1605
不知归路
不知归路 2021-01-15 05:28

I\'m new to Python and could really use some help on this. I want to create a function to filter which files I want to open and which months and day specifically. That way,

相关标签:
3条回答
  • 2021-01-15 05:59

    The best way to do so is just take the required input and convert it into the required case.

    Use the inbuilt functions of python

    variable.lower()
    

    or

    variable.upper()
    
    0 讨论(0)
  • 2021-01-15 06:00

    I am new too but I think you should look at string functions. Presuming you use python 3 since you use input and get no ValueError, you can just add .lover().title() after the parentheses of the input

    Example:

    city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n').lower().title())
    

    Should do the trick as like If you input cHIcaGO it will be converted to Chicago instantly.

    Hope it helps!

    Edit:(After correcting misspelling of lower() function tried it on webbrowser, pycharm and Python itself. Works just fine for me(I'm using python 2.7 so I corrected all inputs as raw_input,If you are using python 3 you don't have to change them. ).)

    0 讨论(0)
  • 2021-01-15 06:08

    You should use str.casefold to remove case sensitivity. As per the docs, this is stricter than str.lower:

    str.casefold()

    Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

    Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

    For example:

    x = 'ßHello'
    
    print(x.casefold())
    
    sshello
    
    0 讨论(0)
提交回复
热议问题