簡體   English   中英

如何刪除字符串中某個字符后的所有內容?

[英]How to delete everything after a certain character in a string?

如何刪除python中字符串的某個字符后的所有內容? 例如,我有一個包含文件路徑和一些額外字符的字符串。 如何在.zip之后刪除所有內容? 我嘗試過rsplitsplit ,但在刪除多余的字符時都沒有包含.zip。

有什么建議么?

只需占用拆分的第一部分,然后添加'.zip'

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

或者你可以使用切片,這里是一個解決方案,你不需要將'.zip'添加回結果( 4來自len('.zip') ):

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

或者正則表達式的另一種選擇

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

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'

使用切片:

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

並且很容易將上面的內容打包成一個小幫手功能:

def removeAfter(string, suffix):
    return string[:string.index(suffix) + len(suffix)]

removeAfter('test.zip.xyz', '.zip')
=> 'test.zip'

您可以使用re模塊:

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

我認為為此創建一個簡單的lambda函數很容易。

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

可以像這樣使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM