如何将文件中的行转换为不带换行符的字符串?

问题描述

我正在使用Python 3遍历包含字符串的.txt文件的各行。这些字符串将在curl命令中使用。但是,它仅在文件的最后一行正常工作。我相信其他行以换行符结尾,这会导致字符串掉:

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

这将返回:

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()将解决您的问题