如何将文件中的行转换为没有换行符的字符串?

How to convert line in file to string without newline?

我正在使用 Python 3 循环遍历包含字符串的 .txt 文件的行。这些字符串将在 curl 命令中使用。但是,它只对文件的最后一行有效。我相信其他行以换行符结尾,这会使字符串消失:

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

这将 return:

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

如何解析所有字符串以像最后一行那样连接?

我看过几个答案,例如 How to read a file without newlines?,但这个答案将文件中的所有内容转换为一行。

使用str.strip

例如:

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

如果字符串以换行符结尾,您可以调用 .strip() 来删除它们。即:

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

我认为 str.strip() 可以解决您的问题