[英]How to delete everything after a certain character in a string?
How would I delete everything after a certain character of a string in python? 如何删除python中字符串的某个字符后的所有内容? For example I have a string containing a file path and some extra characters. 例如,我有一个包含文件路径和一些额外字符的字符串。 How would I delete everything after .zip? 如何在.zip之后删除所有内容? I've tried rsplit
and split
, but neither included the .zip when deleting extra characters. 我尝试过rsplit
和split
,但在删除多余的字符时都没有包含.zip。
Any suggestions? 有什么建议么?
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 4
comes 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)
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'
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'
You can use the re
module: 您可以使用re
模块:
import re
re.sub('\.zip.*','.zip','test.zip.blah')
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.