Home > Software engineering >  Swap upper and lower case with its ASCII value
Swap upper and lower case with its ASCII value

Time:10-18

Im trying to swap letter type with its ASCII value however I am only getting the last word of the string as an output. it also will not accept any string with number values

def get_sentence():
    sentence = input("Please input the sentence:")
    words = sentence.split(' ')
    sentence = ' '.join(reversed(words))
    return sentence

ans = ''

def main():
    sentence = get_sentence()
    ans =''
    for s in sentence:
        if ord(s) >= 97 and ord(s) <= 122:
            ans = ans   chr(ord(s) - 32)
        elif ord(s) >= 65 and ord(s) <= 90 :
            ans = ans   chr(ord(s)   32)
        else :
            ans  = ' '
            print(ans)

if __name__ == "__main__":
    main()

CodePudding user response:

I am not sure if this is the result you want (adding expected output would be helpful next time) but removing the print statement outside the for loop seems to fix it for me.

def get_sentence():
    sentence = input("Please input the sentence:")
    words = sentence.split(' ')
    sentence = ' '.join(reversed(words))
    return sentence

ans = ''

def main():
    sentence = get_sentence()
    ans =''
    for s in sentence:
        if ord(s) >= 97 and ord(s) <= 122:
            ans = ans   chr(ord(s) - 32)
        elif ord(s) >= 65 and ord(s) <= 90 :
            ans = ans   chr(ord(s)   32)
        else :
            ans  = ' '
   
    print(ans) # this should be outside!

if __name__ == "__main__":
    main()

CodePudding user response:

There's a simpler way to do this, using built-in methods isupper() and islower(). Then you don't need to handle sentences (or punctuation) separately.

def swap_case(sentence: str) -> str:
    letters = (
        letter.upper() if letter.islower() else letter.lower()
        for letter in sentence
    )
    return "".join(letters)

print(swap_case(get_sentence()))

Notice my function also returns the result rather than printing it. And it takes input of the sentence, so you can use it in other cases, which makes it more reusable. Not sure why you want the words of the sentence reversed... but ¯\_(ツ)_/¯

  • Related