Last updated: Apr 9, 2024
Reading timeยท5 min
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.
my_str = 'bobbyhadz.com' # โ replace first character in a string new_str = '_' + my_str[1:] print(new_str) # ๐๏ธ _obbyhadz.com
To replace the first N characters in the string, specify a start index of N.
my_str = 'bobbyhadz.com' n = 5 new_str = 'new_' + my_str[n:] print(new_str) # ๐๏ธ new_hadz.com
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.
my_str = 'bobbyhadz.com' print(my_str[1:]) # ๐๏ธ obbyhadz.com
The syntax for string slicing is my_str[start:stop:step]
.
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.
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.
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.
You can also use the str.replace()
method to replace the first or the first N
characters in a string.
my_str = 'bobbyhadz.com' new_str = my_str.replace('b', '_', 1) print(new_str) # ๐๏ธ _obbyhadz.com
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.
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:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only 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.
my_str = 'bobbyhadz.com' new_str = my_str.replace(my_str[0], '_', 1) print(new_str) # ๐๏ธ _obbyhadz.com
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.
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
.
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.
import re my_str = 'bobbyhadz.com' new_str = re.sub('b', '_', my_str, 1) print(new_str) # ๐๏ธ _obbyhadz.com
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.
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.
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.
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.
This is a three-step process:
list()
class to convert the string to a list of characters.str.join()
method to join the list into a string.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
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.
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
.
You can learn more about the related topics by checking out the following tutorials: