我正在使用 Python 3 循環(huán)遍歷包含字符串的 .txt 文件的行。這些字符串將在curl 命令中使用。但是,它僅適用于文件的最后一行。我相信其他行以換行符結(jié)尾,這會導(dǎo)致字符串丟失:url = https://with open(file) as f:? ?for line in f:? ? ? ?str = (url + line)? ? ? ?print(str)這將返回:https://endpoint1https://endpoint2https://endpoint3如何解決所有字符串像最后一行一樣連接的問題?
3 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用str.strip
前任:
url = https://
with open(file) as f:
for line in f:
s = (url + line.strip())
print(s)

互換的青春
TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果字符串以換行符結(jié)尾,您可以調(diào)用.strip()將其刪除。IE:
url = https://
with open(file) as f:
for line in f:
str = (url + line.strip())
print(str)
添加回答
舉報(bào)
0/150
提交
取消