Search code examples
pythonpython-3.xloopsfilestring-concatenation

How to convert line in file to string without newline?


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.


Solution

  • Use str.strip

    Ex:

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