Search code examples
pythonurlpython-requestspython-3.6

How to modify a yarl.URL object?


I am trying to update the path of a relative url using python requests. My request.rel_url object (datatype = <class 'yarl.URL'>) has the following value:

/date/v6/cal?week=three&day=mon

I would like to replace 'v6' here with 'v7' so that my updated URL is:

/date/v7/cal?week=three&day=mon

I have used string replace in python but looks like we cannot use that here with a yarl.URL object.

Any suggestions on how I can update this URL object, while retaining its datatype?


Solution

  • You can convert it to a string, then use the str.replace method:

    print(str(your_object).replace('v6', 'v7'))
    

    After you have the url, you can convert it back to a yarl.URL object.