The strings may have any casing. Rock, ROCK, roCK are all possible and valid. Anyone can help on how to allow my code to accept any case like rOcK and all... ?
player1 = input('Enter rock/paper/scissors: ')
player2 = input('Enter rock/paper/scissors: ')
if (player1 == player2):
print("The game is a Tie")
elif (player1 == 'rock' and player2 == 'scissors'):
print("player 1 wins")
elif (player1 == 'rock' and player2 == 'paper'):
print("player 2 wins")
elif (player1 == 'paper' and player2 == 'rock'):
print("player 1 wins")
elif (player1 == 'paper' and player2 == 'scissors'):
print("player 2 wins")
elif (player1 == 'scissors' and player2 == 'paper'):
print("player 1 wins")
elif (player1 == 'scissors' and player2 == 'rock'):
print("player 2 wins")
else:
print("Invalid input")
My code is perfectly running just can't figure out how to code to allow it accept any case.
-
Does this answer your question? How do I do a case-insensitive string comparison?Carlos Horn– Carlos Horn2023年01月13日 08:49:38 +00:00Commented Jan 13, 2023 at 8:49
2 Answers 2
You can use string.lower() or string.upper() in Python, which converts the string to lower/upper case letters. This way you can have your string all upper or all lower, whichever you want.
f.e: if player1='ROCK' and you compare by player1.lower(), your player1 will be evaluated as rock instead of ROCK
string.lower() documentation:
The lower() method converts all uppercase characters in a string into lowercase characters and returns it.
Comments
You can accept the inputs in any case and convert both inputs to same case before writing the conditions like this:
player1 = input('Enter rock/paper/scissors: ')
player2 = input('Enter rock/paper/scissors: ')
player1 = player1.lower()
player2 = player2.lower()
# then continue with if cases
2 Comments
str.lower works here, but is not the general way for caseless comparison of strings. This is what str.casefold is made for.