Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Swapcase in Python
2.1.
Important points
3.
Using swapcase() to handle strings in python
3.1.
Syntax for Swapcase() in Python
3.2.
Parameters for Swapcase() in Python
3.3.
Return Value for Swapcase() in Python
4.
Examples for Swapcase() in Python
4.1.
Example1: Swapping lowercase to uppercase and uppercase to lowercase using swapcase() in python
4.2.
Python
4.3.
Example 2: swapcase() with string containing special characters
4.4.
Python
4.5.
Example 3: Not necessarily, s.swapcase().swapcase() == s
4.6.
Python
4.7.
Example 4: Real-world Use of swapcase()
4.8.
Python
4.9.
Alternative of swapCase() in Python
4.10.
Example of Alternative of swapCase() in Python 
4.11.
Python
5.
Frequently Asked Questions
5.1.
What does Swapcase () do in Python?
5.2.
What is Swapcase () in Python?
5.3.
What is the alternative for Swapcase in Python?
5.4.
How do you swap case of letters in Python?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python String Swapcase() Method

Author Sanjana Yadav
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

The Python string swapcase() method reverses the case of characters in a string, turning uppercase to lowercase and vice versa.

In this article, we will learn about the swapcase() in Python function, how to use it, and its alternatives with the help of examples.

swapcase in python

So, let’s get started!

What is Swapcase in Python

There are two parallel sets of letters used in uppercase and lowercase writing systems, and each letter in one set often has an equivalent in the other. Lowercase letters are smaller and shorter forms of letters (such as a), in contrast to uppercase letters, which are larger and taller (such as A). swapcase() in python is a very helpful method for changing the case of letters in a string in Python. Python swapcase() provides a replica of the string with all case-sensitive characters swapped out.
 

Python swapcase() definition- This is a built-in string function that returns a duplicate of the specified input string by converting all uppercase characters to lowercase and all lowercase characters to uppercase.

Important points

  • The function of swapcase() in python does not change the original string; instead, it returns a new string generated by changing the cases.
  • No modifications are made to numbers or special characters.
  • It is not always the case that str.swapcase().swapcase() == str

Also see, Python Filter Function

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Using swapcase() to handle strings in python

Let us now see various uses of the swapcase() function in python to handle strings:

Syntax for Swapcase() in Python

Let “str” be the name of the string on which swapcase() is performed. Then, the syntax is:

str.swapcase()

Parameters for Swapcase() in Python

The function of swapcase() in python does not take any parameters. 

The Python interpreter will return a TypeError exception if any parameters are passed to the function.

Return Value for Swapcase() in Python

The swapcase() function returns a string in which all uppercase characters are converted to lowercase, and all lowercase characters are converted to uppercase.

Examples for Swapcase() in Python

Example1: Swapping lowercase to uppercase and uppercase to lowercase using swapcase() in python

  • Python

Python

str = 'lower case to upper case using swapcase'
print('String provided:', str)
print('String returned:', str.swapcase())
print('')

str = 'UPPER CASE TO LOWER CASE USING SWAPCASE'
print('String provided:', str)
print('String returned:', str.swapcase())
print('')

str = 'mIxEd CasE UsING SwapCASe'
print('String provided:', str)
print('String returned:', str.swapcase())

Output

String provided: lower case to upper case using swapcase
String returned: LOWER CASE TO UPPER CASE USING SWAPCASE

String provided: UPPER CASE TO LOWER CASE USING SWAPCASE
String returned: upper case to lower case using swapcase

String provided: mIxEd CasE UsING SwapCASe
String returned: MiXeD cASe uSing sWAPcasE

 

Example 2: swapcase() with string containing special characters

If the input string includes characters of various types, such as numerals, signs, symbols, and so on. The function of swapcase() in python ignores such letters and converts alphabetic characters to their corresponding opposite cases.

  • Python

Python

txt = 'CoDinG NinJAS 123456'
print('String provided:', txt)
print('String returned:', txt.swapcase())
print('')

txt = '@!#^&($%* Python Is FUn wITh CoDinG NinJas'
print('String provided:', txt)
print('String returned:', txt.swapcase())

Output

String provided: CoDinG NinJAS 123456
String returned: cOdINg nINjas 123456

String provided: @!#^&($%* Python Is FUn wITh CoDinG NinJas
String returned: @!#^&($%* pYTHON iS fuN WitH cOdINg nINjAS

Example 3: Not necessarily, s.swapcase().swapcase() == s

Let us discuss an example which demonstrates the expression s.swapcase().swapcase() == s.

  • Python

Python

s = "Hello World"

# Apply swapcase() twice and compare with the original string
if s.swapcase().swapcase() == s:
print("s.swapcase().swapcase() == s is True")
else:
print("s.swapcase().swapcase() == s is False")

Output

s.swapcase().swapcase() == s is True

Explanation

In this example, we first define a string s with the value "Hello World". We then apply the swapcase() method twice to s and compare the result with the original string s. If the expression s.swapcase().swapcase() == s evaluates to True, it means that the original string is the same as the result of applying swapcase() twice. Otherwise, it evaluates to False.

Example 4: Real-world Use of swapcase()

One real-world use of the swapcase() method in Python is for text processing tasks, especially when dealing with case-insensitive data or when formatting strings for output consistency. Here's a simple example:

Let's say you're developing a program that interacts with a database where usernames are case-insensitive, but you want to display them in a consistent format where the first letter of each username is capitalized. You might use swapcase() to ensure consistency while preserving the original case-insensitive data.

  • Python

Python

# Sample list of usernames retrieved from a database
usernames = ['rahul_sharma', 'riya_soni', 'PETER_PARKER', 'rohit_sharma']

# Format usernames for display: capitalize the first letter of each username
formatted_usernames = [username.capitalize() for username in usernames]

# Print the formatted usernames
for username in formatted_usernames:
print(username)

Output:

Rahul_sharma
Riya_soni
Peter_parker
Rohit_sharma

Alternative of swapCase() in Python

Python has a variety of string methods, and only a couple can handle operations equivalent (but not exact) to the swapcase() in python function. Some of these functions include isupper(), islower(), isspace(), upper(), and lower(). In the above example of mixed string case, let us now use these functions to get the same results.

Example of Alternative of swapCase() in Python 

  • Python

Python

str = 'mIxEd CasE UsING SwapCASe'

new_str = ''
for s in str:

   # check lowercase characters and convert to uppercase
   if(s.isupper()) == True:
       new_str += (s.lower())

   # check uppercase characters and convert to lowercase
   elif (s.islower()) == True:
       new_str += (s.upper())

   # check whitespace and add a new string
   elif (s.isspace()) == True:
       new_str += s

print('Original String:', str)
print('Changed String:', new_str)

Output

Original String: mIxEd CasE UsING SwapCASe
Changed String: MiXeD cASe uSing sWAPcasE

Frequently Asked Questions

What does Swapcase () do in Python?

The swapcase() in python function returns a string in which all upper case letters are converted to lower case and vice versa.

What is Swapcase () in Python?

swapcase() in Python is a string method that reverses the case of each letter in the string, converting uppercase letters to lowercase and vice versa.

What is the alternative for Swapcase in Python?

An alternative to swapcase() is using upper() and lower() methods interchangeably.

How do you swap case of letters in Python?

To swap the case of letters in Python, use swapcase() method: string.swapcase() reverses the case of each letter in the string.

Conclusion

In this article, we learned about the Python String swapcase() Method. This method offers a convenient way to reverse the case of characters within a string, aiding in data normalization and manipulation tasks. 
We hope this article has clarified your understanding of the String built-in functions in python. You can refer to our blogs to understand more about built-in functions in python.


You can also visit our website to read more such blogs. Make sure you enroll in our courses, take mock tests, solve problems, and interview puzzles. Also, you can prepare for interviews with interview experiences and an interview bundle.

Keep learning and keep growing, Ninjas!

Previous article
Python Set intersection() Method
Next article
Learning sum() Function in Python
Live masterclass