Looping URLs breaks them - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Looping URLs breaks them (/thread-9646.html) |
Looping URLs breaks them - PythonStudent - Apr-21-2018 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 RE: Looping URLs breaks them - snippsat - Apr-21-2018 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))
RE: Looping URLs breaks them - PythonStudent - Apr-21-2018 It works perfectly. You are the best. |