简体   繁体   中英

Python string-based if-statement

I am writing a Python script for a project I am working on, and I am running into an error that I can't figure out. I am fairly new to Python, so I apologize if this is a very amateur question.

I have an if statement that is comparing a string that it got from a text file. it is supposed to take this input, then return a string with a file location depending on what the input was. However, when I run the script, it always resolves to the else clause, even when the input is exactly what it is being compared against.

def findfile(input):
     if input.lower() == 'option a':
          return 'file location a'
     elif input.lower() == 'option b':
          return 'file location b'
     elif input.lower() == 'option c':
          return 'file location c'
     elif input.lower() == 'option d':
          return 'file location d'
     else:
          return 'Invalid Input'

I have checks earlier in the script so that I know that the input being passed is a string. Regardless, even if I passed a string 'option b' , it would return 'Invalid Input' .

Thanks in advance for any and all help!

This might happen if you get input from a file, because the string has a trailing newline. Use strip to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM