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

我正在使用 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

如何解决所有字符串像最后一行一样连接的问题?

SMILET
浏览 83回答 3
3回答

青春有我

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

互换的青春

如果字符串以换行符结尾,您可以调用.strip()将其删除。IE:url = https://with open(file) as f:   for line in f:       str = (url + line.strip())       print(str)

小唯快跑啊

我认为 str.strip() 会解决你的问题
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python