-4

I was doing a code for a basic game and wondered if someone could help me figure out how to format the input.

import random
choice = str(input("1)Rock \n2)Paper\n3)Scissors\n4)Lizard\n5)Spock\nChoice: "))
computer_choice = random.randrange(5)
outcome = " "
if choice == "rock" and computer_choice == 1:
  outcome = "Tie"

Let's say someone was to put Rock instead of rock, or rOCk instead of rock; what can I use do so that the computer will interpret all these strings as the same. Another quick question, say someone was to input

"         RocK" 

Into the input, what could I use to interpret the statement with this many spaces?

3 Answers3

2

I suggest that you use the method str.lower() in order to make all the strings with the same format. Here is an example:

# example string
string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())

# string with numbers
# all alphabets whould be lowercase
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())

Regarding your second question you can delete the white space in different ways:

  • If you want to delete only the ones on the left and on the right you can use str.trip(). Here is an example:
line = " this has whitespaces "
print(line.strip())
  • If you want to delete all the whitespaces I think that the best options is to use str.replace():
line = " this has whitespaces "
print(line.replace(' ',''))
drauedo
  • 641
  • 4
  • 17
2

To get all lowercase you can use method .lower() and to get rid of whitespace, you can use method .strip()

Your code :

import random
choice = str(input("1)Rock \n2)Paper\n3)Scissors\n4)Lizard\n5)Spock\nChoice: ")).strip().lower()
computer_choice = random.randrange(5)
outcome = " "
if choice == "rock" and computer_choice == 1:
  outcome = "Tie"

And input is already a string so you don't need that str()

import random
choice = input("1)Rock \n2)Paper\n3)Scissors\n4)Lizard\n5)Spock\nChoice: ").strip().lower()
computer_choice = random.randrange(5)
outcome = " "
if choice == "rock" and computer_choice == 1:
  outcome = "Tie"
Haze
  • 147
  • 9
0

You can convert the input to lower-case using the .lower() string function.

import random
choice = str(input("1)Rock \n2)Paper\n3)Scissors\n4)Lizard\n5)Spock\nChoice: ")).lower()
computer_choice = random.randrange(5)
outcome = " "
if choice == "rock" and computer_choice == 1:
  outcome = "Tie" 
crispengari
  • 7,901
  • 7
  • 45
  • 53