将大小写与其ASCII值交换



我试图用ASCII值交换字母类型,但我只得到字符串的最后一个字作为输出。它也不会接受任何具有数值的字符串

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()

我不确定这是否是你想要的结果(下次添加预期的输出会有帮助(,但删除for循环之外的print语句似乎可以帮我解决这个问题。

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()

有一种更简单的方法,使用内置的方法isupper()islower()。这样你就不需要单独处理句子(或标点符号(了。

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()))

注意,我的函数也返回结果,而不是打印结果。它接受句子的输入,所以你可以在其他情况下使用它,这使它更可重用。不知道你为什么要颠倒句子的单词。。。但是\_(ツ)_/

最新更新