Replace the first N characters in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 22, 2022

banner

Photo from Unsplash

Replace the first N characters in a String in Python #

To replace the first N characters in a string:

  1. Use string slicing to get a slice of the string after the first N characters.
  2. Use the addition (+) operator to prepend the replacement string to the slice.
main.py
my_str = 'bobbyhadz.com' n = 5 new_str = 'new_' + my_str[n:] print(new_str) # 👉️ new_hadz.com

We used string slicing to get a slice of the string after the first N characters.

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.

The slice my_str[n:] starts at index n and goes to the end of the string.

We used the addition (+) operator to prepend the replacement string to the slice.

If your replacement value is not of type string, use the str() class to convert it to a string.

main.py
my_str = 'bobbyhadz.com' n = 5 new_str = str(1234) + my_str[n:] print(new_str) # 👉️ 1234hadz.com

The values on the left and right-hand sides of the addition (+) operator need to be of compatible types.

Alternatively, you can use the str.replace() method.

Replace the first N characters in a String using str.replace() #

To replace the first N characters in a string:

  1. Use string slicing to get the first N characters of the string.
  2. Use the str.replace() method to replace the characters with the provided replacement.
main.py
my_str = 'bobbyhadz.com' n = 5 new_str = my_str.replace(my_str[:n], 'new_', 1) print(new_str) # 👉️ new_hadz.com

We used string slicing to get the first N characters of the string.

main.py
my_str = 'bobbyhadz.com' n = 5 print(my_str[:n]) # 👉️ bobby

The next step is to use the str.replace() method to replace the substring only once.

The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Notice that we set the count argument to 1 to only replace the substring once in the string.

main.py
my_str = 'bobbyhadz.com' n = 5 new_str = my_str.replace(my_str[:n], 'new_', 1) print(new_str) # 👉️ new_hadz.com

This is important because the string might contain more than one occurrence of the substring.

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.