How Can I Change The Case In Python To Make Upper Case Lower And Vice Versa
Topic 7: Question 4 Write the function changeCase(word) that changes the case of all the letters in a word and returns the new word. Examples >>> changeCase('aPPle') 'AppL
Solution 1:
Use str.swapcase
:
>>> 'aPPle'.swapcase()
'AppLE'
>>> 'BaNaNa'.swapcase()
'bAnAnA'
Solution 2:
My solution to the problem, no need to "manually" change a case of a letter as above.
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
Solution 3:
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)
Solution 4:
#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
Solution 5:
let="alpHabET"
print(let.swapcase())
#o/p == ALPhABet
Post a Comment for "How Can I Change The Case In Python To Make Upper Case Lower And Vice Versa"