如何从字符串中删除最后n个字符?

use*_*219 13 python

如果我有一个字符串并想要删除它的最后4个字符,我该怎么做?

所以,如果我想删除.bmpForest.bmp让它只是Forest 我该怎么办呢?谢谢.

Lev*_*von 37

两个解决方案.

要删除最后4个字符:

s = 'this is a string1234'

s = s[:-4]
Run Code Online (Sandbox Code Playgroud)

产量

'this is a string'
Run Code Online (Sandbox Code Playgroud)

更具体地说,面向文件名,考虑os.path.splitext()意味着将文件名拆分为其基础和扩展名:

import os 

s = "Forest.bmp"
base, ext = os.path.splitext(s)
Run Code Online (Sandbox Code Playgroud)

结果是:

print base
'Forest'

print ext
'.bmp'
Run Code Online (Sandbox Code Playgroud)