Toggle character’s case in a string using Python
In this tutorial, we will learn to toggle the character’s case in a string in Python. Here, we will toggle the character’s case which means if the character is in lower case we will convert it to upper case and vice versa. We will perform the toggle operation using the American Standard Code for Information Interchange (ASCII) values of the characters. If you want the Python program to toggle the character’s case in a string, you are at the right place.
How to toggle a character’s case?
- Every character is uniquely associated with a number which is called ASCII value.
- ASCII value of –
1. upper case character ‘A’ is 65, ‘B’ is 66, …, ‘Z’ is 90.
2. lower case character ‘a’ is 97, ‘b’ is 98, …, ‘z’ is 122.
- The difference between a character in upper case and lower case is 32. So to convert the character’s case, we have to add/subtract 32 from the original character.
1. upper case character to lower case – lower_case = upper_case + 32
2. lower case character to upper case – upper_case = lower_case – 32
Python program to toggle the character’s case in a string
Now, we will see a program that toggles the character’s case in a string and displays the resultant string. The program takes the string from the user as an input. The Python program is given below-
string = input("Enter text : ") toggle_str = '' for i in range(len(string)): if(string[i] >= 'a' and string[i] <= 'z'): toggle_str = toggle_str + chr(ord(string[i]) - 32) elif(string[i] >= 'A' and string[i] <= 'Z'): toggle_str = toggle_str + chr(ord(string[i]) + 32) else: toggle_str = toggle_str + string[i] print("STRING ENTERED BY YOU :", string) print("RESULTANT STRING AFTER TOGGLING CASE :", toggle_str)
Firstly, the program stores the input text in a variable ‘string’. Then using a ‘for’ loop, we traverse from the first character to the last character. If the character is in lower case (a – z), then we convert it to upper case. Else if the character is in upper case (A – Z), then we convert it to lower case. So, the operation of toggling each character is performed. We store the result in a string ‘toggle_str’. Finally, we display the original string and the toggled string as an output.
Python program output
The above Python program displays the string after toggling each character’s case. The output of the above Python program is-
[email protected]:~/python$ python3 toggle.py Enter text : Here IS a String oR SeNtEnCe STRING ENTERED BY YOU = Here IS a String oR SeNtEnCe RESULTANT STRING AFTER TOGGLING CASE = hERE is A sTRING Or sEnTeNcE [email protected]:~/python$
Here, the input text is “Here IS a String oR SeNtEnCe”. So, the program performs the toggling operation on this input string. Finally, the resultant string becomes “hERE is A sTRING Or sEnTeNcE”. So, this toggled string is the output of the Python program.
Thanks for reading this tutorial and I hope it helps you.