Python 如何删除字符串中某个字符后的所有内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17891443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:25:02  来源:igfitidea点击:

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

pythonstringcharacterpython-3.3

提问by ThatGuyJay

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 rsplitand split, but neither included the .zip when deleting extra characters.

如何在python中某个字符串的某个字符后删除所有内容?例如,我有一个包含文件路径和一些额外字符的字符串。我如何删除 .zip 之后的所有内容?我试过rsplitand split,但在删除额外字符时都没有包含 .zip 。

Any suggestions?

有什么建议?

采纳答案by Andrew Clark

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

只需取出拆分的第一部分,然后添加'.zip'回来:

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 4comes from len('.zip')):

或者,您可以使用切片,这是一个不需要添加'.zip'回结果的解决方案(4来自len('.zip')):

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

Or another alternative with regular expressions:

或者使用正则表达式的另一种选择:

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

回答by óscar López

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'

回答by jh314

You can use the remodule:

您可以使用该re模块:

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

回答by Rob?

str.partition:

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'

回答by joente

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

我认为为此创建一个简单的 lambda 函数很容易。

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'