How to delete everything after a certain character in a string?

前端 未结 5 1135
無奈伤痛
無奈伤痛 2021-02-13 20:10

How would I delete everything after a certain character of a string in python? For example I have a string containing a file path and some extra characters. How would I delete e

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 20:15

    Use slices:

    s = 'test.zip.xyz'
    s[:s.index('.zip') + len('.zip')]
    => 'test.zip'
    

    And it's easy to pack the above in a little helper function:

    def removeAfter(string, suffix):
        return string[:string.index(suffix) + len(suffix)]
    
    removeAfter('test.zip.xyz', '.zip')
    => 'test.zip'
    

提交回复
热议问题