How to Convert a Python String to Alternate Cases?

Converting a string to alternate cases means changing characters at even positions to lowercase and odd positions to uppercase (or vice versa). Python provides several approaches to achieve this pattern using for loops, join() method, and regular expressions.

Using For Loop

The most straightforward approach uses a for loop to iterate through each character and apply case conversion based on the index position ?

text = "Welcome to Tutorialspoint"
result = ""

for i in range(len(text)):
    if i % 2 == 0:
        result += text[i].lower()
    else:
        result += text[i].upper()

print("Original:", text)
print("Alternate case:", result)
Original: Welcome to Tutorialspoint
Alternate case: wElCoMe tO TuToRiAlSpOiNt

Using join() Method

The join() method with list comprehension provides a more concise solution ?

text = "Welcome to Tutorialspoint"

result = ''.join([
    text[i].lower() if i % 2 == 0 else text[i].upper() 
    for i in range(len(text))
])

print("Original:", text)
print("Alternate case:", result)
Original: Welcome to Tutorialspoint
Alternate case: wElCoMe tO TuToRiAlSpOiNt

Using Regular Expression

The re.sub() function with a lambda function provides a functional programming approach ?

import re

text = "Welcome to Tutorialspoint"

result = re.sub(r"(.)", lambda match: 
    match.group(1).lower() if match.start() % 2 == 0 
    else match.group(1).upper(), text)

print("Original:", text)
print("Alternate case:", result)
Original: Welcome to Tutorialspoint
Alternate case: wElCoMe tO TuToRiAlSpOiNt

Comparison

Method Readability Performance Best For
For Loop High Good Simple logic, beginners
join() + List Comprehension Medium Best Efficient string operations
Regular Expression Low Slower Complex pattern matching

Conclusion

The join() method with list comprehension is the most efficient approach for simple alternate case conversion. Use for loops for better readability, and regular expressions when dealing with complex string patterns.

Updated on: 2026-03-27T13:37:07+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements