我编写这个函数是为了检测两个字符串是否是字谜。我想把字符串转换成小写字符,以防其中一个字符是大写的,但我写的东西似乎不能正常工作
# 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.")
调用
cad1.lower()
会将此字符串转换为小写,但未使用此值,您可以尝试cad1 = cad1.lower()
编辑: 而且,它使用
if not cad1.islower()
比使用if cad1.islower() == False
更“pythonic”只需无条件转换,并重新分配小写字符串(
str
是不可变的,因此方法返回新字符串,它们不会更改调用它们的字符串):次要提示:为了更正确地处理非英语字母,我建议使用
.casefold()
而不是.lower()
;在其他语言中,这会产生有意义的变化您不需要检查它们是否较低,因为它们将以小写进行比较:
相关问题 更多 >
编程相关推荐