Remove last n characters from string Python | Example code

Get the size of the string and delete the last N characters from a string will work as Remove last n characters from string Python. For this method, you have to use slicing or for loop or regex.

Slicing a specific range of characters in a string

str[start:end]

Example Remove last n characters from string python

Simple example code. Use length method to get string size and then use slice method with minus n last char.

str1 = "Sample Example"
size = len(str1)

res = str1[:size - 7]
print(res)

Output:

Remove last n characters from string Python

How to remove the last 3 characters from string python?

foo = "Sample Example"
foo = foo[:-3]

print(foo)

Output: Sample Exam

Python string cut last n characters

# string [start:end:step]
string = "PythonExamples"
print(string[0:len(string)-1])		
print(string[0:5])		            
print(string[2:6])		            
print(string[-1])		            
print(string[-5:])		            
print(string[1:-4])                 
print(string[-5:-2])	            
print(string[::2])		            

Output:

python string cut last n characters

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.