Python Forum

Full Version: Looping URLs breaks them
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This happens only when looping.
I have been looking for 3 days now, and I did not get anywhere with this.
I have a list of words that need to be placed in a URL, then print the URL on the screen.
This is what I did:

fh = open('words.txt')
for line in fh:
>>> URLa = "https://www.website.com/sub-path/XXXXX"
>>> URLb = "/some-time"
>>> Link = URLa.replace("XXXXX", line)
>>> print(Link + URLb)
fh.close()

The results of the code above is as this:
https://www.website.com/sub-path/WORD1
/some-time

It splits the URL in 2 lines, when obviously it needs to be 1 single line like this:
https://www.website.com/sub-path/WORD1/some-time

Anybody has an answer for me please?
Thanks a lot
Using string formatting and .strip() it should work fine.
Also you have mixed in >>>,in a code run outside of interactive shell there is no >>>.
with open('words.txt') as f:
    url_a = "https://www.website.com/sub-path/XXXXX"
    url_b  = "/some-time"
    for line in f:
        link = url_a.replace("XXXXX", line)
        print(f'{link.strip()}{url_b}')
        # Before 3.6 .foramt()
        #print('{}{}'.format(link.strip(),url_b))
Output:
https://www.website.com/sub-path/word1/some-time https://www.website.com/sub-path/word2/some-time https://www.website.com/sub-path/word3/some-time
It works perfectly. You are the best.