Remove last character from a Python string
This post will discuss how to remove the last character from a string in Python.
1. Using Slicing
A simple approach to remove the last character from a string is using slicing.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'ABCD' s = s[:-1] print(s) # ABC |
If you want to remove the last n characters, you can do:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = 'ABCD' n = 2 s = s[:-n] print(s) # AB |
2. Using rstrip() function
If you need to remove all occurrence of a trailing character, you can use the rstrip function:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = 'A!BCD!!' ch = '!' s = s.rstrip(ch) print(s) # A!BCD |
That’s all about removing the last character from a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)