如果用户输入等于字符串,用 Python 做一些事情
If user input equals string, do something in Python
如果用户输入等于一个字符串,例如,使用相等运算符来做某事if user_input == my_str:
。True
如果用户输入等于字符串,则相等运算符将返回,False
否则返回。
# ✅ If user input equals string, do something user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input == my_str: print('Correct') else: print('String does NOT match') # ------------------------------------------------------- # ✅ If user input equals one of multiple strings, do something user_input = input('Enter your favorite fruit: ') options = ('apple', 'banana', 'kiwi') if user_input in options: print('Correct') else: print('String does NOT match')
第一个示例使用相等 (==) 运算符来检查用户输入是否等于字符串。
user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input == my_str: print('Correct') else: print('String does NOT match')
True
如果左侧和右侧的值相等,则相等运算符返回,False
否则返回。如果您需要检查用户输入是否等于字符串,忽略大小写,将两个字符串都转换为小写。
user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input.lower() == my_str.lower(): print('Correct') else: print('String does NOT match')
The str.lower
method returns a copy of the string with all the cased characters converted to
lowercase.
The method doesn’t change the original string, it returns a new string. Strings
are immutable in Python.
Both strings have to either be lowercase or uppercase to perform a
case-insensitive comparison.
If you need to check if a user input value is equal to one of multiple values,
use the in
operator.
user_input = input('Enter your favorite fruit: ') options = ['apple', 'banana', 'kiwi'] if user_input in options: print('Correct') else: print('String does NOT match')
The
in operator
tests for membership. For example, x in l
evaluates to True
if x
is a
member of l
, otherwise it evaluates to False
.
options = ['apple', 'banana', 'kiwi'] print('apple' in options) # 👉️ True print('melon' in options) # 👉️ False
The example checks if the input value is equal to any of the values in the
options
list.