Python str.swapcase() function


In Python, the str.swapcase() method is used to create a new string where all uppercase letters are converted to lowercase and all lowercase letters are converted to uppercase. It effectively swaps the case of each letter in the string.

Syntax

str.swapcase()

Example Usage

  1. Basic usage:
text = "Hello World" result = text.swapcase() print(result) # Output: "hELLO wORLD"
  1. All uppercase letters:
text = "PYTHON PROGRAMMING" result = text.swapcase() print(result) # Output: "python programming"
  1. All lowercase letters:
text = "python programming" result = text.swapcase() print(result) # Output: "PYTHON PROGRAMMING"
  1. Mixed case:
text = "Python Is Fun" result = text.swapcase() print(result) # Output: "pYTHON iS fUN"
  1. Including non-alphabetic characters:

Non-alphabetic characters (like numbers, punctuation, and spaces) remain unchanged:

text = "Hello 123!" result = text.swapcase() print(result) # Output: "hELLO 123!"

Important Notes

  • The swapcase() method does not modify the original string; instead, it returns a new string with the case swapped.
  • This method is particularly useful for toggling the case of letters in a string for formatting purposes or text manipulation.

Summary

  • Use str.swapcase() to convert all uppercase letters to lowercase and all lowercase letters to uppercase in a string.
  • It creates and returns a new string with the swapped case of each character while leaving non-alphabetic characters unchanged.