Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the last n characters from a string?

Tags:

python

If I have a string and want to remove the last 4 characters of it, how do I do that?

So if I want to remove .bmp from Forest.bmp to make it just Forest How do I do that? Thanks.

like image 284
user1319219 Avatar asked May 18 '12 02:05

user1319219


1 Answers

Two solutions here.

To remove the last 4 characters in general:

s = 'this is a string1234'

s = s[:-4]

yields

'this is a string'

And more specifically geared toward filenames, consider os.path.splitext() meant for splitting a filename into its base and extension:

import os 

s = "Forest.bmp"
base, ext = os.path.splitext(s)

results in:

print base
'Forest'

print ext
'.bmp'
like image 68
Levon Avatar answered Oct 19 '22 20:10

Levon