Replace First or First N characters in a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Replace the first or first N characters in a String
  2. Replace the first or the first N characters in a String using replace()
  3. Replace the first or first N characters in a String using re.sub()
  4. Replace the first or first N characters in a String using list()

# Replace the first or first N characters in a String in Python

Use string slicing to replace the first or first N characters in a string.

The slice of the string represents the characters after the first N, so we can prepend the replacement characters using the addition (+) operator.

main.py
my_str = 'bobbyhadz.com' # โœ… replace first character in a string new_str = '_' + my_str[1:] print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

replace first character in string

The code for this article is available on GitHub

To replace the first N characters in the string, specify a start index of N.

main.py
my_str = 'bobbyhadz.com' n = 5 new_str = 'new_' + my_str[n:] print(new_str) # ๐Ÿ‘‰๏ธ new_hadz.com

replace first n characters in string

We used string slicing to replace the first or the first N characters of a string.

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

main.py
my_str = 'bobbyhadz.com' print(my_str[1:]) # ๐Ÿ‘‰๏ธ obbyhadz.com

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 last step is to use the addition (+) operator to prepend the replacement string.

main.py
my_str = 'bobbyhadz.com' new_str = '_' + my_str[1:] print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

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

main.py
my_str = 'bobbyhadz.com' new_str = str(123) + my_str[1:] print(new_str) # ๐Ÿ‘‰๏ธ 123obbyhadz.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 or the first N characters in a String using replace()

You can also use the str.replace() method to replace the first or the first N characters in a string.

main.py
my_str = 'bobbyhadz.com' new_str = my_str.replace('b', '_', 1) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

replace first character in string using replace

The code for this article is available on GitHub

The str.replace() method can be passed a count argument of 1 to only replace the first occurrence of the substring in the string

The same approach can be used to replace the first N characters of the string.

main.py
my_str = 'bobbyhadz.com' new_str = my_str.replace('bob', '___', 1) print(new_str) # ๐Ÿ‘‰๏ธ ___byhadz.com

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.

You can also select the character at index 0 if you don't know the value.

main.py
my_str = 'bobbyhadz.com' new_str = my_str.replace(my_str[0], '_', 1) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com
Setting the count argument to 1 means that we are only going to replace the first occurrence of the substring in the string.

To use this approach to replace the first N characters, use string slicing.

main.py
my_str = 'bobbyhadz.com' n = 3 new_str = my_str.replace(my_str[:n], '___', 1) print(new_str) # ๐Ÿ‘‰๏ธ ___byhadz.com

The slice my_str[:n] starts at index 0 and goes up to, but not including index n.

# Replace the first or first N characters in a String using re.sub()

Alternatively, you can use the re.sub() method.

When the count argument is set to 1, the re.sub() method only replaces the first occurrence of the substring in the string.

main.py
import re my_str = 'bobbyhadz.com' new_str = re.sub('b', '_', my_str, 1) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

replace the first or first n characters in string using re sub

The code for this article is available on GitHub

The re.sub() method can optionally be used with a regular expression.

The same approach works if you need to replace the first N characters in the string.

main.py
import re my_str = 'bobbyhadz.com' new_str = re.sub('bob', '___', my_str, 1) print(new_str) # ๐Ÿ‘‰๏ธ ___byhadz.com

The re.sub() method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

If the pattern isn't found, the string is returned as is.

The first argument we passed to the re.sub() method is the pattern we want to match in the string and the second is the replacement for the match.

The last argument is the count - the maximum number of pattern occurrences to be replaced.

You can also select the character at index 0 if you don't know its value.

main.py
import re my_str = 'bobbyhadz.com' new_str = re.sub(my_str[0], '_', my_str, 1) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

Alternatively, you can use the list() class.

# Replace the first or first N characters in a String using list()

This is a three-step process:

  1. Use the list() class to convert the string to a list of characters.
  2. Update the value of the first element in the list.
  3. Use the str.join() method to join the list into a string.
main.py
my_str = 'bobbyhadz.com' list_of_chars = list(my_str) # ๐Ÿ‘‡๏ธ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z', '.', 'c', 'o', 'm'] print(list_of_chars) list_of_chars[0] = '_' new_str = ''.join(list_of_chars) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com
The code for this article is available on GitHub

We first used the list() class to convert the string to a list of characters.

As opposed to strings, lists are mutable, so we can directly update the value of a list element at a specific index.

The last step is to use the str.join() method to join the list into a string.

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used an empty string separator to join the list into a string without a delimiter.

The same approach can be used to replace the first N characters of a string.

main.py
my_str = 'bobbyhadz.com' list_of_chars = list(my_str) # ๐Ÿ‘‡๏ธ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z', '.', 'c', 'o', 'm'] print(list_of_chars) n = 3 list_of_chars[:n] = '___' new_str = ''.join(list_of_chars) print(new_str) # ๐Ÿ‘‰๏ธ _obbyhadz.com

The slice list_of_chars[:n] starts at index 0 and goes up to, but not including index n.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev