Python String Remove Last n Characters

In Python last characters of a string can be removed with indexes like:

n = 5
'Python is cool'[:-n]
print('Python is cool'[:-n])

result:

Python is

Or with string variable like:

n = 3

mystr = 'Python is cool'
mystr = mystr[:-n]
print(mystr)

result:

Python is c

If you want to deal with spaces and special characters you can try with this piece of code:

n = 3
mystr = 'Python is cool'
mystr = ''.join(mystr.split())[:-n]
print(mystr)

result:

Pythonisc

If you want to remove the n-th character of a string than you can do:

n = 1
print('Python'[:n] + 'Python'[n+1:])
n = 4
print('Python'[:n] + 'Python'[n+1:])

result:

Pthon
Pythn

If you want to remove n-th sequence of a string with a given length than you can do:


n = 1
m = 3
print('Python'[:n] + 'Python'[n+m:])

result:

Pon