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:
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:
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.