如果是大写,如何转换成小写字符串

2024-10-02 00:20:47 发布

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

我编写这个函数是为了检测两个字符串是否是字谜。我想把字符串转换成小写字符,以防其中一个字符是大写的,但我写的东西似乎不能正常工作

# function to check if two strings areanagram or not
def eh_anagrama(cad1, cad2):
    if cad1.islower() == False:
        cad1.lower()
    if cad2.islower() == False:
        cad2.lower()
    if(sorted(cad1)== sorted(cad2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")

Tags: the函数字符串falseif字符lowersorted
3条回答

调用cad1.lower()会将此字符串转换为小写,但未使用此值,您可以尝试cad1 = cad1.lower()

编辑: 而且,它使用if not cad1.islower()比使用if cad1.islower() == False更“pythonic”

只需无条件转换,并重新分配小写字符串(str是不可变的,因此方法返回新字符串,它们不会更改调用它们的字符串):

def eh_anagrama(cad1, cad2):
    cad1 = cad1.lower()  # Reassign to replace with lowercased string
    cad2 = cad2.lower()  # Ditto
    if sorted(cad1) == sorted(cad2):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")

次要提示:为了更正确地处理非英语字母,我建议使用.casefold()而不是.lower();在其他语言中,这会产生有意义的变化

您不需要检查它们是否较低,因为它们将以小写进行比较:

def eh_anagrama(cad1, cad2):
    if sorted(cad1.lower()) == sorted(cad2.lower()):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")

相关问题 更多 >

    热门问题