Python c/ swapcaser problem

Asked

Viewed 39 times

1

The program must convert a letter in schema A->a or a->A and works normally, except that at the end of the string a None appears. Does anyone know how I can get it out?

def swap_case(s):
for x in s:
    if x.isupper()==True:
        print(x.lower(), end="")
    else:
        print(x.upper(), end="")
s = input('Digite: ')
result = swap_case(s)
print(result)

1 answer

5


There appears a None because you’re not returning anything in your function, you’re just printing, change to:

def swap_case(s):
    for x in s:
        if x.isupper()==True:
            return x.lower()
        else:
            return x.upper()
s = input('Digite: ')
result = swap_case(s)
print(result, end="")

Taking advantage to improve:

1- The function isupper already returns a True or False (is Boolean), soon this if x.isupper()==True: can/should be alone if x.isupper():

2- (MOST IMPORTANT) The function does not seem to make much sense so (it will return only the first letter exchanged), because what you should want with "swap_case" is to swap all the letters of the given string, so it doesn’t make sense, what you want is:

def swap_case(s):
    text = ''
    for x in s:
        if x.isupper():
            text += x.lower()
        else:
            text += x.upper()
    return text

s = input('Digite: ')
result = swap_case(s)
print(result)

Input:
Output: Nelson

DEMONSTRATION

Reducing to a line within the function:

def swap_case(s):
    return ''.join(x.lower() if x.isupper() else x.upper() for x in s)

DEMONSTRATION

  • 1

    cool! + 1 ...and by the way; return "".join([chr(ord(x)^32) for x in s])

  • @Good jjoao, so it’s cool too

Browser other questions tagged

You are not signed in. Login or sign up in order to post.