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.
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.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.