SoFunction
Updated on 2024-10-29

Python English word case conversion common method examples

Python Converts English Words to Case

In Python, we can convert the case of English words in several different ways. Here are some common ways:

Using the lower() and upper() methods

These two methods are used to convert strings to lowercase and uppercase, respectively.

word = "Hello World"  
lowercase_word = ()  
print(lowercase_word)  # Output: hello world
uppercase_word = ()  
print(uppercase_word)  # exports: HELLO WORLD

Use the capitalize() method

This method converts the first character of the string to uppercase and the rest to lowercase.

word = "hello world"  
capitalized_word = ()  
print(capitalized_word)  # exports: Hello world

Using the title() method

This method converts the first letter of each word to uppercase and the rest of the characters to lowercase.

word = "hello world"  
title_case_word = ()  
print(title_case_word)  # exports: Hello World

Using the swapcase() method

This method converts uppercase letters to lowercase and lowercase letters to uppercase in a string.

word = "Hello World"  
swap_case_word = ()  
print(swap_case_word)  # exports: hELLO wORLD

Using the casefold() method

This method essentially converts the string to lowercase and removes all case differences. This is often used to perform case-insensitive comparisons.

word = "Hello World"  
case_folded_word = ()  
print(case_folded_word)  # exports: hello world

Case Conversion Using Regular Expressions

Regular expressions are a powerful text processing tool, and Python's re module allows us to use regular expressions for case conversion.

import re  
word = "Hello World"  
lowercase_word = (r"[A-Z]", lambda x: (0).lower(), word)  
print(lowercase_word)  # exports: hello world

The () function takes a regular expression and a replacement function. The regular expression [A-Z] matches all uppercase letters, and the replacement function converts the matched uppercase letters to lowercase.

The above are some common methods for English word case conversion in Python, for more information about Python English case conversion, please pay attention to my other related articles!