Convert Nth character of a String to Uppercase in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Convert Nth character of a String to Uppercase in Python #

To convert the Nth character of a string to uppercase:

  1. Get a string slice up to the specified character.
  2. Select the character and use the str.upper() method to convert it to uppercase.
  3. Append the rest of the string to the result.
main.py
# 👇️ N based on index def uppercase_nth_char(string, index): return string[:index] + string[index].upper() + string[index + 1:] print(uppercase_nth_char('bobby', 2)) # 👉️ boBby print(uppercase_nth_char('hadz', 3)) # 👉️ hadZ print(uppercase_nth_char('com', 1)) # 👉️ cOm # ---------------------------------------------- # 👇️ N based on order of characters def uppercase_nth_char(string, n): return string[:n - 1] + string[n - 1].upper() + string[n:] print(uppercase_nth_char('bobby', 2)) # 👉️ bObby print(uppercase_nth_char('hadz', 3)) # 👉️ haDz print(uppercase_nth_char('com', 1)) # 👉️ Com

The first function converts the character at index N to uppercase.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(my_str) - 1.
main.py
def uppercase_nth_char(string, index): return string[:index] + string[index].upper() + string[index + 1:] print(uppercase_nth_char('bobby', 2)) # 👉️ boBby print(uppercase_nth_char('hadz', 3)) # 👉️ hadZ print(uppercase_nth_char('com', 1)) # 👉️ cOm

The slice string[:index] starts at index 0 and goes up to, but not including the specified index.

We used the str.upper() method to convert the character at the given index to uppercase.

The last step is to append the rest of the string to the result.

Notice that we added 1 to the index because the start index is inclusive.

Alternatively, you can specify N based on the order of the characters in the string.

main.py
def uppercase_nth_char(string, n): return string[:n - 1] + string[n - 1].upper() + string[n:] print(uppercase_nth_char('bobby', 2)) # 👉️ bObby print(uppercase_nth_char('hadz', 3)) # 👉️ haDz print(uppercase_nth_char('com', 1)) # 👉️ Com

We had to subtract 1 because the first character in a string has an index of 0.

The slice string[:n - 1] goes up to, but not including the specified character.

We then convert the character to uppercase and append the rest of the string to the result.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.