João
João

Reputation: 73

How to convert to lower case string if it's in upper case

I'm writing this function to detect if two strings are anagrams. I want to convert the strings into lower case characters in case one of the characters is in upper case, but what I wrote doesn't seem to be working properly.

# 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.")

Upvotes: 2

Views: 766

Answers (4)

SeekNDstroy
SeekNDstroy

Reputation: 322

I made some changes. Instead of just writing cad1.lower() or cad2.lower() I assigned them to the variable corresponding to the value.

cad1 = cad1.lower() and cad2 = cad2.lower()

# function to check if two strings areanagram or not
def eh_anagrama(cad1, cad2):

    cad1 = cad1.lower() ; cad2 = cad2.lower()

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

Upvotes: 0

scandav
scandav

Reputation: 758

You don't need to check if they're lower, as they would be compared in lower case anyway:

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

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155313

Just unconditionally convert, and reassign the lowercased string (str are immutable, so methods return new strings, they don't change the one they're called on):

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.")

Minor side-note: For handling non-English alphabets more correctly, I'd suggest using .casefold() instead of .lower(); in other languages, this can make a meaningful difference.

Upvotes: 0

UdonN00dle
UdonN00dle

Reputation: 723

Calling cad1.lower() will convert this string to lowercase, but this value isn't used, you could try cad1 = cad1.lower()

Edit: Also, it's more "pythonic" using if not cad1.islower() as opposed to if cad1.islower() == False

Upvotes: 0

Related Questions