简体   繁体   English

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

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

If I have a string and want to remove the last 4 characters of it, how do I do that? 如果我有一个字符串并想要删除它的最后4个字符,我该怎么做?

So if I want to remove .bmp from Forest.bmp to make it just Forest How do I do that? 所以,如果我想从Forest.bmp删除.bmp以使其成为Forest我该怎么做? Thanks. 谢谢。

Two solutions here. 两个解决方案。

To remove the last 4 characters in general: 要删除最后4个字符:

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

import os 

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

results in: 结果是:

print base
'Forest'

print ext
'.bmp'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM