How to Capitalize Alternate Letters in a String in Python

When I was working on a text formatting project, I needed to make strings look “stylized” by capitalizing every alternate letter.

At first, I thought Python might have a built-in function for this. But soon, I realized I needed to use a combination of string methods, slicing, and loops to achieve it.

In this tutorial, I’ll show you multiple ways to capitalize alternate letters in a Python string. I’ll also share my firsthand experience with each method so you can pick the one that works best for you.

Methods to Capitalize Alternate Letters in a String in Python

Let me show you the methods to capitalize alternate letters in a string in Python.

1: Use upper() and lower() methods in Python

The upper() and lower() methods are built-in string methods in Python. We utilize these methods to alternate between capitalizing and not capitalizing characters in a string.

Code

text = "united states of america is a diverse country"
capitalized_text = ""

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

print(capitalized_text)

In this code, we iterate through each character in the string. If the index is even, we capitalize the character in Python. Otherwise, we leave it unchanged.

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

Output:

UnItEd sTaTeS Of aMeRiCa iS A DiVeRsE CoUnTrY

You can refer to the screenshot below to see the output.

Alternate the case of each letter in a given string in Python

This method alternates character cases in a string by capitalizing even-indexed characters and lowercasing odd-indexed ones using upper() and lower().

2: Use Python List Comprehension

The list comprehension in Python provides a concise syntax for generating lists based on expressions and optional conditions.

Code:

text = "united states of america is a diverse country"
capitalized_text = ''.join([text[i].upper() if i % 2 == 0 else text[i].lower() for i in range(len(text))])

print(capitalized_text)

In this code, we use list comprehension to iterate through each character in the string. We capitalize characters at even indices and keep others unchanged.

Output

UnItEd sTaTeS Of aMeRiCa iS A DiVeRsE CoUnTrY

You can refer to the screenshot below to see the output.

How to Convert a Python String to Alternate Cases of each character

This method uses list comprehension to efficiently alternate character casing, capitalizing even-indexed characters and lowercasing odd-indexed ones.

3: Use Regex

Here, a regular expression with the re.sub() function is used to match every character in the string and alternate between capitalizing and not capitalizing them in Python.

Code

import re

text = "united states of america is a diverse country"
capitalized_text = re.sub(r'(\w)(\w)', lambda m: m.group(1).upper() + m.group(2), text)

print(capitalized_text)

This code uses re.sub() based on a custom lambda function in Python. The lambda function capitalizes characters at even indices and keeps others unchanged.

Output

UnItEd StAtEs Of AmErIca Is a DiVeRse CoUnTry

You can refer to the screenshot below to see the output.

program to capitalize every alternate letter in python

This method uses re.sub() with a lambda function to alternate character casing, capitalizing the first character in each matched pair.

4: Use Python’s find() method

The find() method is the built-in method of Python, which is used to find the index of the first occurrence of a substring in a string.

Here, we use it to determine the position of each character in the string and alternate between capitalizing and not capitalizing them.

Code

greeting = "Hello everyone, I am Peter Parker"

formatted_greeting = greeting.lower().replace(" ","")
print("The original string is : " + (greeting))
res = ""
loweralpha = "abcdefghijklmnopqrstuvwxyz"
upperalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0, len(formatted_greeting)):
	if(i % 2 == 0):
		res += upperalpha[loweralpha.find(formatted_greeting[i])]
	else:
		res += loweralpha[loweralpha.find(formatted_greeting[i])]

print("The alternate case string is : " + str(res))

We are using the same logic that we’ve used in the previous example with the find() method in Python.

Output

The original string is : Hello everyone, I am Peter Parker
The alternate case string is : HeLlOeVeRyOnEzIaMpEtErPaRkEr

You can refer to the screenshot below to see the output.

capitalize alternate letters in Python

This method uses find() with custom alphabets to alternate character casing by converting letters at even indices to uppercase and others to lowercase.

5: Use Recursion in Python

Recursion in Python programming refers to a technique where a function calls itself to solve a problem.

Code

def alternate_cases(s, i=0):
	if i == len(s):
		return ""
	return (s[i].upper() if i % 2 == 0 else s[i].lower()) + alternate_cases(s, i+1)

population = "Population of USA is 330 million people"

print("The original string is : " + str(population))

res = alternate_cases(population)

print("The alternate case string is : " + str(res))

This code defines a recursive function that capitalizes characters at even indices and leaves others unchanged.

def alternate_cases(s, i=0):
	if i == len(s):
		return ""
	return (s[i].upper() if i % 2 == 0 else s[i].lower()) + alternate_cases(s, i+1)

Output

The original string is : Population of USA is 330 million people
The alternate case string is : PoPuLaTiOn oF UsA Is 330 mIlLiOn pEoPlE

You can refer to the screenshot below to see the output.

how to capitalize every other letter in Python

This method uses recursion to alternate character casing by capitalizing letters at even indices and converting others to lowercase.

6: Use map and lambda

The map() function returns a map object of the results after applying the given function to each item of a given Python string, and a lambda function can take any number of arguments. Still, it can only have one expression in Python.

Code

about_country = "The United States is known for its economic power, technological innovation, and cultural influence"
result = "".join([about_country[i].upper() if i%2==0 else about_country[i].lower() for i in range(len(about_country))])
print(result) 

This lambda function in Python is applied to each index of the input string using map(), producing a sequence of modified characters. Finally, these modified characters are concatenated into a single string using ” .join() and printed.

"".join([about_country[i].upper() if i%2==0 else about_country[i].lower() for i in range(len(about_country))])

Output:

ThE UnItEd sTaTeS Is kNoWn fOr iTs eCoNoMiC PoWeR, tEcHnOlOgIcAl iNnOvAtIoN, aNd cUlTuRaL InFlUeNcE

You can refer to the screenshot below to see the output.

Alternate upper and lower in python

This method uses map() and lambda to alternate character casing efficiently, capitalizing even-indexed characters and lowercasing the rest.

7: Use zip() and join() Methods in Python

Here we will use the zip() function to aggregate elements from two iterables, so it takes two or more data sets and “zips” them together, and join() to create a string with alternate capitalization in Python.

Code

information = "the United States is one of the most populous countries in the world."
print("original string is: ",information)
res = "".join("".join(x) for x in zip(information[0::2].upper(), information[1::2].lower()))
print("alternate case string is : " + res)

In this code, characters at even and odd indices are zipped together, then capitalized and joined into a string.

Output

original string is:  the United States is one of the most populous countries in the world.
alternate case string is : ThE UnItEd sTaTeS Is oNe oF ThE MoSt pOpUlOuS CoUnTrIeS In tHe wOrLd

You can refer to the screenshot below to see the output.

change alternate cases in python

This method uses zip() and join() to pair and combine characters, creating a string with alternating uppercase and lowercase letters.

8: Use Python’s split() and join() Methods

The split() method returns a list of substrings, where each substring is separated by whitespace by default in Python.

Code

def alternate_cases(string):
	return ''.join([''.join(char.upper() if i%2 == 0 else char.lower() for i, char in enumerate(word)) for word in string.split()])

country = " United States of America dynamiccountry with a rich history and vast natural beauty."
print("The original string is: ",country)

res = alternate_cases(country)
print("The alternate case string is : " + res)

In this code, the Python string is split into words, and then list comprehension is used to iterate through each character within each word. Alternate characters are capitalized and then joined back into a single string.

Output:

The original string is:   United States of America dynamiccountry with a rich history and vast natural beauty.
The alternate case string is : UnItEdStAtEsOfAmErIcADyNaMiCcOuNtRyWiThARiChHiStOrYAnDVaStNaTuRaLBeAuTy.

You can refer to the screenshot below to see the output.

Capitalize Alternate Letters in a String in Python

This method splits the string into words, alternates the case of characters within each word, and joins them back into a single formatted string.

Conclusion

Here, we’ve explored various methods to capitalize alternate letters in a string in Python, utilizing built-in methods such as upper() and lower() to more advanced approaches like regular expressions and recursion or list comprehensions, the find() method, or using functions like map() and zip().

Each method offers its advantages depending on the specific requirements of the task.

You may also like to read the following articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.