To capitalize every other letter of a string in Python, the easiest way is with a loop inside a function.
def capitalize_every_other(string):
result = ""
prev_char_cap = False #we want first letter to be capitalized
for char in string:
if prev_char_cap:
result = result + char.lower()
else:
result = result + char.upper()
prev_char_cap = not prev_char_cap
return result
print(capitalize_every_other("programming"))
#Output:
PrOgRaMmInG
If you have a string with spaces, and want to take spaces into account, then you can do the following.
def capitalize_every_other(string):
result = ""
prev_char_cap = False #we want first letter to be capitalized
for char in string:
if prev_char_cap:
result = result + char.lower()
else:
result = result + char.upper()
if char != " ":
prev_char_cap = not prev_char_cap
return result
print(capitalize_every_other("programming is fun"))
#Output:
PrOgRaMmInG iS fUn
When working with strings in Python, the ability to easily manipulate and change the value of a string variable can be useful.
One such situation is if you want to capitalize every other letter of a string.
You can easily capitalize every other letter of a string in Python using a loop and the upper() and lower() functions.
First, we need to create an empty string and then also decide if we want the first letter to be capitalized or not.
Then, you can loop over each character in the string and if the previous character is capitalized, then we make the character lowercase. If the previous character is lowercase, then we make it uppercase.
Below is a function in Python which will capitalize every other character in a string.
def capitalize_every_other(string):
result = ""
prev_char_cap = False #we want first letter to be capitalized
for char in string:
if prev_char_cap:
result = result + char.lower()
else:
result = result + char.upper()
prev_char_cap = not prev_char_cap
return result
print(capitalize_every_other("programming"))
#Output:
PrOgRaMmInG
If you have a string with spaces, and want to take spaces into account, then you need one additional step. If the character is a space, then we shouldn’t update the previous character variable.
def capitalize_every_other(string):
result = ""
prev_char_cap = False #we want first letter to be capitalized
for char in string:
if prev_char_cap:
result = result + char.lower()
else:
result = result + char.upper()
if char != " ":
prev_char_cap = not prev_char_cap
return result
print(capitalize_every_other("programming is fun"))
#Output:
PrOgRaMmInG iS fUn
Hopefully this article has been useful for you to learn how to capitalize every other letter in a string using Python.
Leave a Reply