In this article, we will discuss different ways to replace the first N characters of a string with another substring in Python.
Table Of Contents
Suppose we have a string,
"Sample String"
We want to replace the first 3 characters in this string. After replacement, the final string should be like,
"XXXple String"
There are different techniques to do this. Let’s discuss them one by one.
Frequently Asked:
Using Indexing
To replace the first N characters in a string using indexing, select all characters of string except the first n characters i.e. str[n:]. Then add these characters after the new replacement substring and assign it back to the original variable. It will give us an effect that we have replaced the first N characters in string with a new substring.
For example: Replace first 3 characters in a string with “XXX”
strValue = 'Sample String' n = 3 replacementStr = 'XXX' # Replace First 3 characters in string with 'XXX' strValue = replacementStr + strValue[n:] print(strValue)
Output:
XXXple String
It replaced the first 3 characters in string with “XXX”.
Latest Python - Video Tutorial
Using replace()
In Python, the string class provides a member function replace(substring, replacement, count) . It helps to do the replacement in the string. It accepts three arguments,
- substring
- replacement
- count
It returns a copy of the original string with the modified content. Basically in the copied string, it replaces the first count occurrences of substring with the replacement substring.
We can use this to replace the first N characters in string. For that we need to pass following arguments,
- Substring containing first n characters of calling string object.
- Replacement string
- 1; to replace only the first occurrence of substring.
For example: Replace first 3 characters in a string with “XXX”
strValue = 'Sample String' n = 3 replacementStr = 'XXX' # Replace First 3 characters in string with 'XXX' strValue = strValue.replace(strValue[0 : n], replacementStr, 1) print(strValue)
Output:
XXXple String
It replaced the first 3 characters in string with “XXX”.
Using Regex
The regex module has a function regex.sub(pattern, replacement_str, original_str) . It helps to replace the substrings that matches the given regex pattern.
To replace only the first N character in a string, we will pass the regex pattern “^.{0,N}” and replacement substring in the sub() function. This regex pattern will match only the first N characters in the string and those will be replaced by the given character.
For example: Replace first 3 characters in a string with “XXX”
import re strValue = 'Sample String' # Replace First 3 characters in string with 'XXX' strValue = re.sub(r'^.{0,3}', 'XXX', strValue) print(strValue)
Output:
XXXple String
Summary:
We learned about three different ways to replace the first N characters in a string in Python.
Latest Video Tutorials