在Python中从字符串中删除子字符串?

2024-09-30 20:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我´我目前面临的问题是,我有一个字符串(deeplink),我想从中提取一个子字符串:

   <deeplink>https://www.jsox.de/tokyo-l200/tokio-skytree-ticket-fuer-einlass-ohne-anstehen-t107728/?partner_id=M1</deeplink>

   <deeplink>https://www.jsox.de/tokyo-l201/ganztaegige-bustour-zum-fuji-ab-tokio-t65554/?partner_id=M1</deeplink>

我希望从上面的字符串中提取以下信息:

t107728
t65554

例如,如何仅从上面的第一个字符串中提取子字符串t107728? 我尝试了拆分和子函数,但没有成功

你们能帮帮我吗?任何反馈都将不胜感激


Tags: 字符串httpsidpartnerwwwdetokyom1
2条回答

您可以使用split函数来尝试此操作:

strings = ["<deeplink>https://www.jsox.de/tokyo-l200/tokio-skytree-ticket-fuer-einlass-ohne-anstehen-t107728/?partner_id=M1</deeplink>", "<deeplink>https://www.jsox.de/tokyo-l201/ganztaegige-bustour-zum-fuji-ab-tokio-t65554/?partner_id=M1</deeplink>"]

results = [elem.split("/?")[0].split("-")[-1] for elem in strings]

print(results)

输出:

['t107728', 't65554']

您可以使用re

import re
s = ['<deeplink>https://www.jsox.de/tokyo-l200/tokio-skytree-ticket-fuer-einlass-ohne-anstehen-t107728/?partner_id=M1</deeplink>', '<deeplink>https://www.jsox.de/tokyo-l201/ganztaegige-bustour-zum-fuji-ab-tokio-t65554/?partner_id=M1</deeplink>']
new_s = [re.findall('[a-zA-Z0-9]+(?=/\?)', i)[0] for i in s]

输出:

['t107728', 't65554']

相关问题 更多 >