Home > Blockchain >  Doing Anagram with case insensitive in python
Doing Anagram with case insensitive in python

Time:11-15

Good day Guys! I'm a beginner at python. I wanted to make a program that does anagram with comparing two strings but I can't make a condition that also accepts both upper/and lowercase

str1 = input("Enter First String: ")
str2 = input("Enter Second String: ") 
#for white spaces
str1=''.join(str1.split())
str2=''.join(str2.split())

#to sort
#to check if they can be sorted equally, to check if the string is empty 
if (sorted(str1) == sorted(str2) and (len(str1)) and (len(str2))):
    
 print("Strings are anagram") 
else:
 print("Strings are not anagram")

CodePudding user response:

you can use .lower, .upper or .casefold to ignore case.
(.lower converts everything to lowercase, .upper converts everything to uppercase and .casefold works just like .lower but it is more strict (e.g. the german letter ß equivalent to ssbut because it's lowercase .lower doesn't do anything but .casefold will convert this to ss))

In your case you should add this in your condition:

if (sorted(str1.lower()) == sorted(str2.lower()) and (len(str1)) and (len(str2))):

full code:

str1 = input("Enter First String: ")
str2 = input("Enter Second String: ") 
#for white spaces
str1=''.join(str1.split())
str2=''.join(str2.split())

#to sort
#to check if they can be sorted equally, to check if the string is empty 
if (sorted(str1.lower()) == sorted(str2.lower()) and (len(str1)) and (len(str2))):
    
 print("Strings are anagram") 
else:
 print("Strings are not anagram")
  • Related