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
Example Usage
- Basic usage:
- All uppercase letters:
- All lowercase letters:
- Mixed case:
- Including non-alphabetic characters:
Non-alphabetic characters (like numbers, punctuation, and spaces) remain unchanged:
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.