1

I'm using Python 3 to loop through lines of a .txt file that contains strings. These strings will be used in a curl command. However, it is only working correctly for the last line of the file. I believe the other lines end with newlines, which throws the string off:

url = https://
with open(file) as f:
   for line in f:
       str = (url + line)
       print(str)

This will return:

https://
endpoint1
https://
endpoint2
https://endpoint3

How can I resolve all strings to concatonate like the last line?

I've looked at a couple of answers like How to read a file without newlines?, but this answer converts all content in the file to one line.

Rakesh
  • 81,458
  • 17
  • 76
  • 113
Yunter
  • 274
  • 3
  • 17

3 Answers3

2

Use str.strip

Ex:

url = https://
with open(file) as f:
   for line in f:
       s = (url + line.strip())
       print(s)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

If the strings end with newlines you can call .strip() to remove them. i.e:

url = https://
with open(file) as f:
   for line in f:
       str = (url + line.strip())
       print(str)
MauroNeira
  • 315
  • 3
  • 13
1

I think str.strip() will solve your problem

ogre
  • 48
  • 4