SoFunction
Updated on 2025-05-20

Several common ways to convert strings to lowercase letters in Python

In Python, there are several ways to convert uppercase letters in a string to lowercase letters. Here are some commonly used methods:

1. Use the built-in method lower() (the easiest)

Python string objects come withlower()Method, you can directly convert all uppercase letters to lowercase, and other characters remain unchanged.

Sample code

s = "Hello, WORLD!"
result = ()
print(result)  # Output: "hello, world!"

2. Manual traversal + ASCII code conversion

You can traverse each character in a string and use the ASCII code value (ord()andchr()) Manually convert capital letters (A-Z's ASCII range is 65-90).

Sample code

s = "Hello, WORLD!"
result = ""
for char in s:
    if 65 <= ord(char) <= 90:  # Check if it is capital letters        result += chr(ord(char) + 32)  # uppercase to lowercase (ASCII difference is 32)    else:
        result += char
print(result)  # Output: "hello, world!"

3. Use () (performance optimization)

pass()Create a conversion table and use ittranslate()Methods batch replace characters, suitable for processing large amounts of text.

Sample code

s = "Hello, WORLD!"
# Create a conversion table: Map A-Z to a-ztrans_table = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
                           'abcdefghijklmnopqrstuvwxyz')
result = (trans_table)
print(result)  # Output: "hello, world!"

4. Use list comprehension (concise writing method)

Combinedchr()andord(), generate a new string using list comprehension.

Sample code

s = "Hello, WORLD!"
result = ''.join(
    chr(ord(c) + 32) if 'A' <= c <= 'Z' else c
    for c in s
)
print(result)  # Output: "hello, world!"

Summarize

method advantage Applicable scenarios
() Simple and efficient Daily development (recommended)
Manual ASCII conversion Flexible control of conversion rules Custom conversion logic
() high performance Processing large amounts of text
List comprehension One-line code implementation Pursuing code simplicity

This is the article about several commonly used methods of converting strings into lowercase letters in Python. For more related content on Python string conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!