gpt4 book ai didi

python - 如何在 Python 中使用 Regex/Strip() 去除字符串末尾的随机字符?

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:50 24 4
gpt4 key购买 nike

在 Python 中截断字符串末尾的随机字符的首选方法是什么?

我正在尝试简化 URL 列表以进行一些分析,因此需要截掉文件扩展名 .php 之后的所有内容

由于 .php 之后的字符对于每个 URL 都是不同的,因此使用 strip() 不起作用。我考虑了正则表达式和 substring()。但是解决这个任务最有效的方法是什么?

示例:

假设我有以下网址:

example.com/index.php?random_var=random-19wdwka
example.org/index.php?another_var=random-2js9m2msl

我希望输出为:

example.com/index.php
example.org/index.php

感谢您的建议!

最佳答案

有两种方法可以实现您想要的目标。

如果你知道字符串如何结束:

在您的示例中,如果您知道字符串以 .php 结尾? 那么您需要做的就是:

my_string.split('?')[0]

如果您不知道字符串如何结束:

在这种情况下,您可以使用 urlparse 并获取除参数之外的所有内容。

from urlparse import urlparse

for url is urls:
p = urlparse(url)
print p.scheme + p.netloc + p.path

关于python - 如何在 Python 中使用 Regex/Strip() 去除字符串末尾的随机字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com