Python string swapcase() method

Python String swapcase() Method

Description

The swapcase() method returns a copy of a string with the case of all characters swapped.

Syntax

The following is the syntax of the swapcase() method −

var.swapcase()

Parameters

None

Return Value

This method returns a copy of a string with the case of all characters swapped.

Example

The following example demonstrates the use of the swapcase() method −

var = "This Is String Example....WOW!!!"
var1 = var.swapcase()
print ("original string:", var)
print ("Case Swapped:", var1)

When we run the above program, it produces the following output

original string: This Is String Example....WOW!!!
Case Swapped: tHIS iS sTRING eXAMPLE....wow!!!

In the following example, all the case conversion methods of the str class are used −

var="Hello python"

var1=var.upper()
var2=var.lower()
var3=var.title()
var4=var.capitalize()
var5=var.casefold()
var6=var.swapcase()

print ("original string: ", var)
print ("upper case:", var1)
print ("lowercase: ", var2)
print ("title case:", var3)
print ("capitalized:",var4)
print ("casefolded:", var5)
print ("case swapped:", var6)

It will produce the following Output −

original string: Hello python
upper case: HELLO PYTHON
lowercase: hello python
title case: Hello Python
capitalized: Hello python
casefolded: hello python
case swapped: hELLO PYTHON

In the above example, these methods are used as instance methods. Python’s str class also has static versions of all of these methods. For example, capitalizing a string: −

var.capitalize()

This can also be achieved as follows:

str.capitalize(var)

The following example uses all static methods for case conversion: −

var="Hello python"

var1=str.upper(var)
var2=str.lower(var)
var3=str.title(var)
var4=str.capitalize(var)
var5=str.casefold(var)
var6=str.swapcase(var)

print ("original string: ", var)
print ("upper case: ", var1)
print ("lower case: ", var2)
print ("title case: ", var3)
print ("capitalized:",var4)
print ("casefolded:", var5)
print ("case swapped:", var6)

It will produce the following output

original string: Hello python
upper case: HELLO PYTHON
lowercase: hello python
title case: Hello Python
capitalized: Hello python
casefolded: hello python
case swapped: hELLO PYTHON

Leave a Reply

Your email address will not be published. Required fields are marked *