修改Python 2中的URL组件

修改Python 2中的URL组件,python,url,python-2.x,urlparse,Python,Url,Python 2.x,Urlparse,在Python2中有没有更干净的方法来修改URL的某些部分 比如说 http://foo/bar -> http://foo/yah 目前,我正在这样做: import urlparse url = 'http://foo/bar' # Modify path component of URL from 'bar' to 'yah' # Use nasty convert-to-list hack due to urlparse.ParseResult being immutable

在Python2中有没有更干净的方法来修改URL的某些部分

比如说

http://foo/bar -> http://foo/yah
目前,我正在这样做:

import urlparse

url = 'http://foo/bar'

# Modify path component of URL from 'bar' to 'yah'
# Use nasty convert-to-list hack due to urlparse.ParseResult being immutable
parts = list(urlparse.urlparse(url))
parts[2] = 'yah'

url = urlparse.urlunparse(parts)

是否有更清洁的解决方案?

不幸的是,文档已过时;
urlparse.urlparse()
(和
urlparse.urlplit()
)生成的结果使用a作为基础

不要将此namedtuple转换为列表,而是使用为该任务提供的实用程序方法:

parts = urlparse.urlparse(url)
parts = parts._replace(path='yah')

url = parts.geturl()
用于创建替换了特定图元的新副本。然后,将这些部分重新连接到url中

演示:


提交了一份文件来解决文档问题。

我想正确的方法是这样做

由于使用
\u不建议替换
私有方法或变量

from urlparse import urlparse, urlunparse

res = urlparse('http://www.goog.com:80/this/is/path/;param=paramval?q=val&foo=bar#hash')
l_res = list(res)
# this willhave ['http', 'www.goog.com:80', '/this/is/path/', 'param=paramval', 'q=val&foo=bar', 'hash']
l_res[2] = '/new/path'
urlunparse(l_res)
# outputs 'http://www.goog.com:80/new/path;param=paramval?q=val&foo=bar#hash'

你说的“干净”到底是什么意思?我想指出这一点。由
namedtuple
返回的子类向
urlparse.ParseResult
提供实用程序方法。我认为应该在2.7文档中指出这一点,因为如果不知道这一点,您就无法知道
\u replace
实际上是这个类的公共API的一部分……更有趣的是,在文档中提到的,它根本没有出现在源代码中。。。(很抱歉离题了…已经晚了…+1)@mgilson:嘿,的确,那一定是使用
namedtuple
之前的遗留问题。谢谢-这是一个更好的解决方案。虽然,正如其他评论所指出的,仅仅从文档来看,似乎没有办法知道它。@GarethStockwell:是的,看起来像一个文档bug;还没有归档,我稍后会这么做。它是公共界面的一部分,只是加了underscrore前缀,以避免与实际成员冲突。
from urlparse import urlparse, urlunparse

res = urlparse('http://www.goog.com:80/this/is/path/;param=paramval?q=val&foo=bar#hash')
l_res = list(res)
# this willhave ['http', 'www.goog.com:80', '/this/is/path/', 'param=paramval', 'q=val&foo=bar', 'hash']
l_res[2] = '/new/path'
urlunparse(l_res)
# outputs 'http://www.goog.com:80/new/path;param=paramval?q=val&foo=bar#hash'