Skip to main content

Command Palette

Search for a command to run...

Python replace last character in string

Published
2 min readView as Markdown
J

I am a full stack developer, who also writes on Kodlogs.net

##Introduction This article will show you how Python replace last character in string, To be able to get the solution, you should know what string slicing and indexing mean. And that is what this article will introduce to you.

##How to replace last character in string Let’s start with indexing! In fact, Strings can be indexed (subscripted), with the first character having an index of 0. There is no separate character type; a character is simply a string of size one, last characters can be indexed from right to left with a negative index which the last character is -1.

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'
>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

Then let’s move to slice! While indexing is used to obtain individual characters, slicing allows you to obtain substring. Also, Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced. Note how the start is always included, and the end is always excluded. This makes sure that s[:i] + s[i:] is always equal to s.

>>> word = “Python”
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

To remove replace last character in string, we should get all characters except last character then add it to the character to be replaced with.

##Solution 1 This solution will be with slicing.

>>> word = “Python3” # we want it to be python 2
>>> word = word[:-1] + “2# remember position -1 (excluded)
>>> print(word)
“Python2”

##Solution 2

This solution will be with slicing and formatting

>>> source = 'Python3'
>>> result = "{}{}".format({source[0: -1], '2')
>>> print(result)
“Python2”

###In general We should use string slicing to be able to get replace the last character in the string.

##Conclusion The easiest method to replace the last character in a string is string slicing, formatting a string is a harder and longer solution. Also, Indexing is essential to be able to achieve this.

More from this blog

Untitled Publication

39 posts