迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 中如果用户输入等于某个字符串则做一些事情

作者:迹忆客 最近更新:2022/12/20 浏览次数:

如果用户输入等于字符串,请使用相等运算符来执行某些操作,例如 if user_input == my_str:。 如果用户输入等于字符串,则相等运算符将返回 True,否则返回 False。

# ✅ 如果用户输入等于某个字符串则做一些事情

user_input = input('Enter your favorite fruit: ')

my_str = 'apple'

if user_input == my_str:
    print('Correct')
else:
    print('String does NOT match')

# -------------------------------------------------------

# ✅ 如果用户输入等于多个字符串之一,则执行某些操作

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')

str.lower 方法返回字符串的副本,其中所有大小写字符都转换为小写。

该方法不会更改原始字符串,它会返回一个新字符串。 字符串在 Python 中是不可变的。

两个字符串都必须是小写或大写才能执行不区分大小写的比较。

如果我们需要检查用户输入值是否等于多个值之一,请使用 in 运算符。

user_input = input('Enter your favorite fruit: ')

options = ['apple', 'banana', 'kiwi']

if user_input in options:
    print('Correct')
else:
    print('String does NOT match')

in 运算符测试成员资格。 例如,如果 x 是 l 的成员,则 x in l 的计算结果为 True,否则计算结果为 False

options = ['apple', 'banana', 'kiwi']

print('apple' in options)  # 👉️ True

print('melon' in options)  # 👉️ False

该示例检查输入值是否等于选项列表中的任何值。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便