Alternate cases in String - Python
Last Updated :
08 Feb, 2025
The task of alternating the case of characters in a string in Python involves iterating through the string and conditionally modifying the case of each character based on its position. For example, given a string s = "geeksforgeeks", the goal is to change characters at even indices to uppercase and those at odd indices to lowercase, producing a string where the case alternates for each character.
Using list comprehension
When applied to the problem of alternating case in a string, list comprehension allows for a clean one liner that loops over the string, applying a conditional check on each character's index to determine whether to convert it to uppercase or lowercase. This method is efficient in terms of both time and space, as it processes each character exactly once and joins them into a string in one go.
Python
s = "geeksforgeeks"
res = ''.join([s[i].upper() if i % 2 == 0 else s[i].lower() for i in range(len(s))])
print(res)
Explanation: list comprehension iterates over each character in s, converting it to uppercase for even indices and lowercase for odd indices and then ''.join() combines the resulting list of characters into a single string.
Using map()
map() can be used in conjunction with a lambda function to transform each character in the string based on its index. This method allows for a more functional programming approach, where we avoid explicit loops, but it may be less efficient than list comprehension for beginners.
Python
s = "geeksforgeeks"
res = ''.join(map(lambda x: x[1].upper() if x[0] % 2 == 0 else x[1].lower(), enumerate(s)))
print(res)
Explanation: map() with a lambda function iterates over the string and alternates the case based on whether the index is even or odd and then result joined into a single string using ''.join().
str.format() allows dynamic string formatting, making it a useful tool for alternating the case of letters in a string. By using str.format() inside a loop, we can conditionally check each character’s index and apply either uppercase or lowercase formatting based on whether the index is even or odd.
Python
s = "geeksforgeeks"
res = ""
for idx, char in enumerate(s):
res += '{}'.format(char.upper() if idx % 2 == 0 else char.lower())
print(res)
Explanation: for loop with enumerate() iterates over the string, using str.format() to alternate the case based on the index and the formatted characters are concatenated into the result string res.
Using for loop
A traditional for loop checks each character's index to alternate its case based on whether the index is even or odd. While simple , this method can be less efficient due to repeated string concatenation, leading to higher memory usage and slower performance for larger strings. However, it's a common approach for beginners to handle string manipulation tasks.
Python
s = "geeksforgeeks"
res = ""
for idx in range(len(s)):
if not idx % 2:
res += s[idx].upper()
else:
res += s[idx].lower()
print(res)
Explanation: for loop iterates over the string by index, converting characters at even indices to uppercase and those at odd indices to lowercase, then concatenates them into the res string.
Similar Reads
Python - Alternate Strings Concatenation The problem of getting the concatenation of a list is quite generic and we might someday face the issue of getting the concatenation of alternate elements and get the list of 2 elements containing the concatenation of alternate elements. Letâs discuss certain ways in which this can be performed. Met
3 min read
Reverse Alternate Characters in a String - Python Reversing alternate characters in a string involves rearranging the characters so that every second character is reversed while maintaining the original order of other characters. For example, given the string 'abcde', reversing the alternate characters results in 'ebcda', where the first, third and
3 min read
How to Create String Array in Python ? To create a string array in Python, different methods can be used based on the requirement. A list can store multiple strings easily, NumPy arrays offer more features for large-scale data and the array module provides type-restricted storage. Each method helps in managing collections of text values
2 min read
String Interning in Python String interning is a memory optimization technique used in Python to enhance the efficiency of string handling. In Python, strings are immutable, meaning their values cannot be changed after creation. String interning, or interning strings, involves reusing existing string objects rather than creat
2 min read
Insert a number in string - Python We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Swap elements in String list - Python Swapping elements in a string list means we need to exchange one element with another throughout the entire string list in Python. This can be done using various methods, such as using replace(), string functions, regular expressions (Regex), etc. For example, consider the original list: ['Gfg', 'is
3 min read