'Convert All String Values to Lower/Uppercase in Python

I want to use a list of string values in an if statement and convert any input given by the user to lowercase- the only way I can do this now is by making a list that includes all lowercase and uppercase values and then use the "in" and "not in" operators in the if statement. Here's my code:

yes = [
    "Y", "y", "yes", "YES"]
no = [
    "N", "n", "no", "NO"]


start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if start in yes:
    main()
elif start in no:
    print("Hope you can play some other time!")

There are other longer lists in the same program and this makes it very inconvenient to type different variations of the same word. Is there any way I can convert all values to lower/upper case either in the list itself, or in the if statement?



Solution 1:[1]

You can use the builtin function lower:

start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start in ['y', 'yes']:
    main()
elif start in ['n', 'no']:
    print("Hope you can play some other time!")

And if you want without the list at all, you can check only the first letter:

start = input("Hello there! Press 'y' to start, or 'n' to stop. ").lower()
if start[0] == 'y':
    main()
elif start[0] == 'n':
    print("Hope you can play some other time!")

Solution 2:[2]

inp = input('Enter: ').upper()
print(inp)

This will print the input in uppercase. user lower() to convert in lowercase.

Solution 3:[3]

You might like to use strtobool. This will obviate the need to upper()|lower() and will convert truthy values into True|False for you.

from distutils.util import strtobool
start = input("Hello there! Press 'y' to start, or 'n' to stop. ")
if strtobool(start):
    main()
else:
    print("Hope you can play some other time!")

True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

Solution 4:[4]

I would do it like this:

start = input("Hello there! Press 'y' to start, or 'n' to stop. ").upper()[0]
    if start == "Y":
print("put main program here")
    else:
print("Hope you can play some other time!")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Irfan wani
Solution 3
Solution 4 Pebo muc