如何在Python中更改大小写以使大写字母更低,反之亦然

时间:2014-12-01 15:12:33

标签: python string python-2.7

主题7:问题4 编写改变单词中所有字母大小写的函数changeCase(word)并返回新单词。

实施例

>>> changeCase('aPPle')
"AppLE"
>>> changeCase('BaNaNa')
'bAnAnA'

我是python的初学者,我的错误在哪里?

def changeCase(word):
    return ''.join(c.upper() if c in 'aeiou' else c.lower() for c in word)

6 个答案:

答案 0 :(得分:12)

使用str.swapcase

>>> 'aPPle'.swapcase()
'AppLE'
>>> 'BaNaNa'.swapcase()
'bAnAnA'

答案 1 :(得分:1)

我对问题的解决方案,无需"手动"改变上面一封信的情况。

def changeCase(word):
    newword = ""                     # Create a blank string
    for i in range(0, len(word)):
        character = word[i]          # For each letter in a word, make as individual viarable
        if character.islower()== False: # Check if a letter in a string is already in upper case
            character = character.lower()  # Make a letter lower case
            newword += character           # Add a modified letter in a new string
        else:
            character = character.upper()  # Make a letter upper case
            newword += character           # Add a modified letter in a new string

    return newword                         # Return a new string

答案 2 :(得分:-1)

def swap_case(s):
    input_list = list(s)
    return "".join(i.lower() if i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" else i.upper() for i in input_list)

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

答案 3 :(得分:-1)

#Here is another example to convert lower case to upper case and vice versa   
while not bothering other characters:
#Defining function
def swap_case(s):
    ls=[]
    str=''
    # converting each character from lower case to upper case and vice versa and appending it into list
    for i in range(len(s)):
        if ord(s[i]) >= 97:
            ls.append(chr((ord(s[i]))-32)) #ord() and chr() are inbuild methods
        elif ord(s[i]) >= 65 and ord(s[i]) <97:
             ls.append(chr((ord(s[i]))+32))
        # keeping other characters
        else:
            ls.append(chr(ord(s[i])))
    # converting list into string
    for i in ls:
        str+=i
    return(str)
if __name__ == '__main__':
    s = input()
    # calling function swap_case()
    result = swap_case(s)
    print(result)


input: www.SWAPCASE@program.2
Output: WWW.swapcase@PROGRAM.2

答案 4 :(得分:-2)

let="alpHabET"

print(let.swapcase())

#o/p == ALPhABet

答案 5 :(得分:-2)

txt  = "aPpLe"
print (txt.swapcase())

SwapCase 函数将返回字符串的副本,其中大写字符转换为小写,反之亦然。

更多信息:请参阅文档here