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

前端 未结 5 1136
無奈伤痛
無奈伤痛 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:35

    Just take the first portion of the split, and add '.zip' back:

    s = 'test.zip.zyz'
    s = s.split('.zip', 1)[0] + '.zip'
    

    Alternatively you could use slicing, here is a solution where you don't need to add '.zip' back to the result (the 4 comes from len('.zip')):

    s = s[:s.index('.zip')+4]
    

    Or another alternative with regular expressions:

    import re
    s = re.match(r'^.*?\.zip', s).group(0)
    

提交回复
热议问题