如何使字符串检查不区分大小写? [英] How to make string check case insensitive?

查看:57
本文介绍了如何使字符串检查不区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习Python,作为一种练习,我正在研究基于文本的冒险游戏。现在,该代码实际上是无效的,因为它检查用户的响应以查看它是否与同一单词的多个变体相同。如何更改它,使字符串检查不区分大小写?

I've started learning Python recently and as a practise I'm working on a text-based adventure game. Right now the code is really ineffective as it checks the user responce to see if it is the same as several variations on the same word. How do I change it so the string check is case insensitive?

以下示例代码:

if str('power' and 'POWER' and 'Power') in str(choice):
    print('That can certainly be found here.')
    time.sleep(2)
    print('If you know where to look... \n')


推荐答案

if 'power' in choice.lower():

应该做的(假设 choice 是一个字符串)。如果选择 包含单词 power ,这将是正确的。如果要检查是否相等,请使用 == 代替中的

should do (assuming choice is a string). This will be true if choice contains the word power. If you want to check for equality, use == instead of in.

此外,如果您要确保将次幂仅作为一个整体匹配(而不作为 horsepower的一部分) powerhouse ),然后使用正则表达式:

Also, if you want to make sure that you match power only as a whole word (and not as a part of horsepower or powerhouse), then use regular expressions:

import re
if re.search(r'\bpower\b', choice, re.I):

这篇关于如何使字符串检查不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆