在python中使用ignorecases的位置

2024-06-16 09:41:28 发布

您现在位置:Python中文网/ 问答频道 /正文

对不起,我的英文写得不好,我希望你理解我的要求,我对python非常陌生,我需要som帮助处理区分大小写的变量。我原以为使用正则表达式会有帮助,但我可能想错了。 我想让用户键入歌曲标题,看看标题是否已经存在。 我已经有一个测试数据“伤害”,“约翰尼现金”。 因此,如果用户键入“Hurt”,它将打印出“Title exists”,但如果用户键入带有小写字母的“Hurt”,它将打印出(“Title not exists”)

有什么提示或帮助我如何确保它忽略大小写敏感?你知道吗

代码如下:

在Python中,我制作了类名Song

class Song(object):

    #Constructor
    def __init__(self, title, artist):

        #Instance variabler
        self._title = title
        self._artist = artist                                                                         

    def checkTitle(self, title):
       #RegEX
       m = re.search(r"([a-zA-Z0-9]*)[\s]([a-zA-Z0-9]*)",title)
       songTitle = t.group(0)
       print (songTitle) # prints out "hurt" in lower cases from user input(look below the code)

       if sangTittel == self._title:
            print("Title exists")
       else:
           print("Title not exists")                                                              

newSong = Song("Hurt", "Johnny Cash")                                                           
title = input("Write the name of the songtitle: ") #user write hurt in lower cases  

checkTitle(title)

Tags: the用户self标题键入songtitleartist
3条回答

最好的办法是把所有的事情都用小写字母表示。你知道吗

def checkTitle(self, title): 
    songTitle = t.lower() 
    print (songTitlle) 
   if songTittel == self._title: 
       print("Title exists") 
    else: 
       print("Title not exists")

并在__init__方法中执行相同的操作。你知道吗

self._title = title.lower()

注意

您还有capitalize方法,这可能很有趣。你知道吗

你不需要正则表达式。你知道吗

就像Reza说的,你可以用upper()或者lower()来解决这个问题,然后用in来检查标题。你知道吗

if title.lower() in self._title.lower()

Python中,可以使用str.upper()str.lower()方法返回转换为大写/小写的字符串副本。对于您的代码,您可以像这样使用它:

checkTitle(title.lower())

输入小写字母。你知道吗

相关问题 更多 >