How to Capitalize Alternate Letters in a String in Python [8 Ways]

Are you interested in capitalizing alternate letters in your Python strings? This Python tutorial will explore five different methods to capitalize alternate letters in a string in Python.

Capitalizing alternate letters in a string is a part of text processing. We’ll see different Python techniques, such as string manipulation, list comprehensions, regular expressions, and more, to accomplish this task efficiently and effectively.

Capitalize alternate letters in a string in Python

Here is the list of all the methods to capitalize alternate letters in a string in Python:

  • Using upper() and lower() method
  • Using list comprehension
  • Using Regular Expressions
  • Using find() method
  • Using Recursion
  • Using map and lambda function
  • Using join() and zip() method
  • Using split() and join() method

Let’s dive into these methods:

Capitalize alternate letters in Python using upper() and lower() methods

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.

Let’s see an instance to capitalize alternate letters in a string in Python:

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

The screenshot is mentioned below after implementing the code in the Python editor.

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

Alternate Capitalization of every character using List Comprehension

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

READ:  How to Compare Two Strings Character by Character in Python [5 different ways]

Here is how we can use list comprehension to capitalize alternate letters in a string in Python.

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

A screenshot is mentioned below, after implementing the code in the Python editor.

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

Alternate case of every character in Python using 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.

Here is an instance to use the re.sub() function 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

After executing the code in Python, one can see the output in the below screenshot.

program to capitalize every alternate letter in python

How to capitalize alternate characters using the 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 the string.

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

A Python program to capitalize alternate letters in a string using the find() function:

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 done 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

Below is a screenshot displaying the output following the implementation of the code in the Python editor.

capitalize alternate letters in Python

Alternate Uppercase and Lowercase using Recursion in Python

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

READ:  Python program to display the current date and time

Let’s see the example of capitalizing alternate letters using recursion in Python.

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

 PoPuLaTiOn oF UsA Is 330 mIlLiOn pEoPlE

Below is a screenshot showcasing the output captured after the code was executed in the Python editor.

how to capitalize every other letter in Python

Python Program to Capitalize Alternate letters using 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.

Here is an example:

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

Following the implementation of the code in the Python editor, the screenshot below has been provided.

Alternate upper and lower in python

Capitalize Alternate letters in Python using zip() and join()

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.

READ:  Add two binary numbers 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

The following screenshot was captured after the Python editor implemented the code.

change alternate cases in python

Program to Capitalize Every Alternate Letter using split() and join()

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

Here is an example to capitalize alternate letters in a string 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 dynamic country with a rich history and vast natural beauty.
The alternate case string is : UnItEdStAtEsOfAmErIcADyNaMiCCoUnTrYWiThARiChHiStOrYAnDVaStNaTuRaLBeAuTy.

Refer to the screenshot below for a better understanding:

Capitalize Alternate Letters in a String in Python

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: