We can easily swap the cases of characters in string using the python inbuilt swapcase() function.
Casing swapping is simply changing upper case character to lower case character and lower case character to upper case character.
For example:
If we swap case the string "helloWorld" we will get "HELLOwORLD".
Example of using python swapcase()
Swap the cases in the string "Welcome to Tano Space".
string = "python IS A PROGRAMMING language"
new_string = swapcase(string)
print(new_string)
//it will return "PYTHON is a programming LANGUAGE"
It's simple right? Yes. But assuming you are in a technical interview for a python developer role, and the interviewer asked you to write a python thats swap the cases of characters in a string. You can't use the swapcase() function. How then will you be able to achieve such ?
The code below depict one of the ways to write the code.
Let me show you how
string = "python IS A PROGRAMMING language"
new_string = []
for i in string:
#check if the character is a upper case letter
if i.isupper():
#if the character is upper case the change it to lower
#case
i.lower()
# add the converted character to the list
new_string.append(i)
else:
i.upper()
new_string.append(i)
#use the join() to combine the items of the list
print("".join(new_string)
Top comments (2)
The whole working code here in below:
Hi, Bro this is not working. Unless you use
new_string.append(i.lower())
in if condition and vice verse of else conditioni.upper()
of the code.