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

放肆的年华 提交于 2019-12-12 07:47:28

问题


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 everything after .zip? I've tried rsplit and split , but neither included the .zip when deleting extra characters.

Any suggestions?


回答1:


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)



回答2:


str.partition:

>>> s='abc.zip.blech'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.zip'
>>> ''.join(s.partition('.zip')[0:2])
'abc.zip'
>>> s='abc.py'
>>> ''.join(s.partition('.zip')[0:2])
'abc.py'



回答3:


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'



回答4:


You can use the re module:

import re
re.sub('\.zip.*','.zip','test.zip.blah')



回答5:


I think it's easy to create a simple lambda function for this.

mystrip = lambda s, ss: s[:s.index(ss) + len(ss)]

Can be used like this:

mystr = "this should stay.zipand this should be removed."
mystrip(mystr, ".zip") # 'this should stay.zip'


来源:https://stackoverflow.com/questions/17891443/how-to-delete-everything-after-a-certain-character-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!