This article will discuss different ways to replace the last character of a string in Python.
Table Of Contents
Suppose we have a string,
"Sample String"
After replacing the last character of this string with “X”, the final string should be,
"Sample StrinX"
There are different ways to replace the last character of a string in Python. Let’s discuss them one by one.
Using Indexing
In Python, we can select the sub-strings from a string based on index range using the subscript operator. For example, str[start:end] will select the substring from index position start to end.
Using this, we can select a substring from a string, that should contain characters from the start of string till the second last character of string, i.e. str[:-1]. It will give us a substring containing all the characters of the original string except the last character. The we can add new character at the end of this substring. It will give us the effect that we have replaced the last character of a string.
Frequently Asked:
- Check if a String is Empty in Python
- Remove multiple character from a string in Python
- How to split and parse a string in Python?
- Convert string to float in python
For Example:
strValue = 'Sample String' replacementStr = 'X' # Replace last character of string with 'X' strValue = strValue[:-1] + replacementStr print(strValue)
Output:
Sample StrinX
It replaced the string’s last character with the character ‘X’.
Using rsplit() and join()
Split the string but from reverse direction i.e. starting from the end and while moving towards the front of string. Use the last character of string as delimeter and 1 as the max count of split i.e. strValue.rsplit(strValue[-1:], 1) . It will return a sequence of characters in string except the last character. Then join these characters to the character ‘X’ using the join() function.
For Example:
strValue = 'Sample String' replacementStr = 'X' # Replace last character of string with 'X' strValue = replacementStr.join(strValue.rsplit(strValue[-1:], 1)) print(strValue)
Output:
Sample StrinX
It replaced the string’s last character with the character ‘X’.
Using Regex
The regex module has a function regex.sub(pattern, replacement_str, original_str) and it replacees the contents of a string based on the regex pattern match.
To replace only the last character in a string, we will pass the regex pattern “.$” and replacement character in sub() function. This regex pattern will match only the last character in the string and that will be replaced by the given character.
For Example:
import re strValue = "Sample String" # Replace last character of string with 'X' strValue = re.sub(r".$", "X", strValue) print(strValue)
Output:
Sample StrinX
It replaced the string’s last character with the character ‘X’.
Summary:
We learned different ways to replace the last character of a string in Python.