Hi I have a question about the following code:
str1 = "Race"
str2 = "Care"
# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
Race en Care are now anagrams, but how to make an anagram with sentences:
For example: str1 = "Race is good"
str2 = "Careisgood" They are also an anagram, but it gives that it is not an anagram. I think because the spaces. How to skip the spaces?
>Solution :
To remove spaces from a string, you can use the replace(" ", "") method.
str1 = "Race is good"
str2 = "Careisgood"
# convert both the strings into lowercase
str1 = str1.lower().replace(" ", "")
str2 = str2.lower().replace(" ", "")
# check if length is same
if(len(str1) == len(str2)):
# sort the strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# if sorted char arrays are same
if(sorted_str1 == sorted_str2):
print(str1 + " and " + str2 + " are anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")
else:
print(str1 + " and " + str2 + " are not anagram.")