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

前端 未结 1 1202
旧巷少年郎
旧巷少年郎 2020-12-03 14:26

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

相关标签:
1条回答
  • 2020-12-03 14:59

    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'
    
    0 讨论(0)
提交回复
热议问题