猿问

从特定点删除文本

我想删除可能与 python 中的特定点不同的文本部分

前任:

lksalksapointdlksla
删除“point”
pointdlksla之前的所有内容

kljkghglpointsdfasfsd
删除“point”
pointsdfasfsd之前的所有内容

这可能吗?


阿波罗的战车
浏览 86回答 3
3回答

陪伴而非守候

您可以使用正则表达式:import reregex = r"(?P<before>.*)(point)(?P<after>.*)"test_str = "lksalksapointdlksla"matches = re.finditer(regex, test_str, re.MULTILINE)for matchNum, match in enumerate(matches, start=1):&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for groupNum in range(0, len(match.groups())):&nbsp; &nbsp; &nbsp; &nbsp; groupNum = groupNum + 1&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))然后,您可以使用before和after组来执行您喜欢的操作。

叮当猫咪

我将使用.find()字符串切片:s = 'lksalksapointdlksla's = s[s.find('point'):]print(s)

森栏

你能行的:text = "kljkghglpointsdfasfsd"text = text.split("point")[1]print(text)
随时随地看视频慕课网APP

相关分类

Python
我要回答