Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping URLs breaks them
#1
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
Reply
#2
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
Reply
#3
It works perfectly. You are the best.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tie Breaks klatlap 6 1,138 Mar-20-2023, 12:08 PM
Last Post: klatlap
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 2,004 Apr-05-2021, 05:40 PM
Last Post: deanhystad
  How to Remove Non-ASCII Characters But Leave Line Breaks In Place? bmccollum 4 4,321 Apr-09-2020, 07:59 PM
Last Post: DeaD_EyE
  Detect end of line in text file including line breaks DanielM 4 3,199 Dec-18-2019, 11:57 AM
Last Post: Malt
  Using Python to search through a list of urls jeremy 4 2,878 Dec-18-2019, 11:52 AM
Last Post: Malt
  Urls in a file to be executed pyseeker 2 2,046 Sep-09-2019, 03:38 PM
Last Post: pyseeker
  user validation for opening urls Ashley 6 2,730 Jul-08-2019, 09:08 PM
Last Post: metulburr
  oop breaks mepyyeti 7 4,288 Dec-26-2017, 07:20 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020