如何删除字符串中某个字符后的所有内容? [英] How to delete everything after a certain character in a string?
问题描述
如何删除python中字符串的某个字符后的所有内容?例如,我有一个包含文件路径和一些额外字符的字符串。我如何删除.zip之后的所有内容?我尝试过 rsplit
和 split
,但是在删除多余的字符时没有包括.zip。
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.
任何建议?
推荐答案
只需取第一部分, code>'。zip'返回:
Just take the first portion of the split, and add '.zip'
back:
s = 'test.zip.zyz'
s = s.split('.zip', 1)[0] + '.zip'
$ b b
或者你可以使用切片,这里是一个解决方案,你不需要添加'。zip'
回到结果> 4 来自 len('。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)
这篇关于如何删除字符串中某个字符后的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!