modifying parts of a urlparse.SplitResult
Peter Otten
__peter__ at web.de
Tue Jan 12 07:46:43 EST 2016
Tim Chase wrote:
> I can successfully parse my URLs. However, I'd like to modify a part
> then reassemble them. However, like tuples, the parts appear to be
> unmodifiable
>
> >>> URL = 'http://foo/path1/path2/?fragment=foo'
> >>> import urlparse
> >>> u = urlparse.urlparse(URL)
> >>> u
> ParseResult(scheme='http', netloc='foo', path='/path1/path2/',
> params='', query='fragment=foo', fragment='')
> >>> u.query
> 'fragment=foo'
> >>> u.query = 'blah=baz'
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: can't set attribute
>
> The best I've been able to come up with is
>
> >>> u = urlparse.urlsplit(URL)
> >>> lst = list(u) # can't manipulate the tuple directly
> >>> lst[3] = "bar=baz" # 3 = query-string index
> >>> urlparse.urlunsplit(lst)
> 'http://foo/path1/path2/?bar=baz'
>
> It takes knowing that "3" is the magic index (documented, but not
> given some named-constant in urlparse) for the query-string. Is
> there some better, clearer, or more Pythonic way to do this?
To allow more fieldnames namedtuples use method names starting with an
underscore. You can safely use them, they are not private. So:
>>> pr = urlparse.urlparse("http://foo/path1/path2/?fragment=foo")
>>> urlparse.urlunparse(pr._replace(query="bar=baz"))
'http://foo/path1/path2/?bar=baz'
More information about the Python-list
mailing list