我有以下代码:
with open(path, 'r') as f:
data = f.readlines()
print("x "+ data[1] + "y")
data[1]
是 txt 文件中的字符串。我得到的结果:
>>> x 10
>>> y
但我希望“y”与“x 10”在同一行。可以用 Python 做吗?
先谢谢你!
答案 0 :(得分:1)
听起来您想从数据 [1] 中去除 '\n'。
您可以在此链接中找到它。 How to read a file without newlines?
答案 1 :(得分:1)
你可以使用替换
>>>test = "the\n line"
>>>print(test)
the
line
>>>print(test.replace("\n",""))
the line
答案 2 :(得分:0)
请注意 data[1] is the string from the txt file
不准确。 data[1] 是文件的第二行。
data = [line.rstrip() for line in f.readlines()]