如何在 Python 中使用 Regex / Strip() 去除字符串末尾的随机字符?
How to strip random Chars at the end of a String with Regex / Strip() in Python?
在 Python 中切断字符串末尾随机字符的首选方法是什么?
我正在尝试简化 URL 的列表以进行一些分析,因此需要切断文件扩展名 .php
之后的所有内容
由于 .php
之后的字符对于每个 URL 都是不同的,因此使用 strip() 不起作用。我想到了正则表达式和 substring()
。但是解决这个任务最有效的方法是什么?
示例:
假设我有以下 URLs:
example.com/index.php?random_var=random-19wdwka
example.org/index.php?another_var=random-2js9m2msl
我希望输出为:
example.com/index.php
example.org/index.php
感谢您的建议!
for url in urls:
result = url.split('?')[0]
print(result)
有两种方法可以完成你想要的。
如果您知道字符串的结尾:
在您的示例中,如果您知道字符串以 .php?
结尾,那么您需要做的就是:
my_string.split('?')[0]
如果您不知道字符串是如何结束的:
在这种情况下,您可以使用 urlparse 并获取除参数以外的所有内容。
from urlparse import urlparse
for url is urls:
p = urlparse(url)
print p.scheme + p.netloc + p.path
在你的分隔符上最多拆分一次,取第一块:
text="example.com/index.php?random_var=random-19wdwka"
sep="php"
rest = text.split(sep)[0]+".php"
print rest
看来你真正想要的是剥离掉URL的参数,你也可以使用
from urlparse import urlparse, urlunparse
urlunparse(urlparse(url)[:3] + ('', '', ''))
将 URL 的参数、查询和片段部分替换为空字符串并生成一个新字符串。
在 Python 中切断字符串末尾随机字符的首选方法是什么?
我正在尝试简化 URL 的列表以进行一些分析,因此需要切断文件扩展名 .php
由于 .php
之后的字符对于每个 URL 都是不同的,因此使用 strip() 不起作用。我想到了正则表达式和 substring()
。但是解决这个任务最有效的方法是什么?
示例:
假设我有以下 URLs:
example.com/index.php?random_var=random-19wdwka
example.org/index.php?another_var=random-2js9m2msl
我希望输出为:
example.com/index.php
example.org/index.php
感谢您的建议!
for url in urls:
result = url.split('?')[0]
print(result)
有两种方法可以完成你想要的。
如果您知道字符串的结尾:
在您的示例中,如果您知道字符串以 .php?
结尾,那么您需要做的就是:
my_string.split('?')[0]
如果您不知道字符串是如何结束的:
在这种情况下,您可以使用 urlparse 并获取除参数以外的所有内容。
from urlparse import urlparse
for url is urls:
p = urlparse(url)
print p.scheme + p.netloc + p.path
在你的分隔符上最多拆分一次,取第一块:
text="example.com/index.php?random_var=random-19wdwka"
sep="php"
rest = text.split(sep)[0]+".php"
print rest
看来你真正想要的是剥离掉URL的参数,你也可以使用
from urlparse import urlparse, urlunparse
urlunparse(urlparse(url)[:3] + ('', '', ''))
将 URL 的参数、查询和片段部分替换为空字符串并生成一个新字符串。