Yunter
Yunter

Reputation: 284

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.

Upvotes: 1

Views: 1195

Answers (3)

ogre
ogre

Reputation: 48

I think str.strip() will solve your problem

Upvotes: 1

MauroNeira
MauroNeira

Reputation: 445

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)

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Use str.strip

Ex:

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

Upvotes: 2

Related Questions