Python 否"\";但新的生产线正在制造中?

Python 否"\";但新的生产线正在制造中?,python,python-3.x,Python,Python 3.x,我的代码中没有\n,但当我打印出所有变量时,它会创建一个换行,这意味着我的最后一个变量打印在另一行上 我的代码: with open("read_it.txt", "r") as text_file: for items in text_file: line = items.split(",") if GTIN in items: product = line[1] indprice = line[2]

我的代码中没有
\n
,但当我打印出所有变量时,它会创建一个换行,这意味着我的最后一个变量打印在另一行上

我的代码:

with open("read_it.txt", "r") as text_file:
    for items in text_file:
        line = items.split(",")
        if GTIN in items:
           product = line[1]
           indprice = line[2]
           finprice = float(indprice)* float(Quantity)
           print(GTIN,product,Quantity,"£",indprice,"£",finprice)
电流输出(错误):

我想:

86947367 banana 2 £ 0.50 £ 1.0

非常感谢您的帮助。

当您在文件对象上调用readline(您在for循环中隐式地执行此操作)时,它会保留结尾的“\n”和/或“\r”字符。在这种情况下,indprice变量仍然包含尾随的“\n”

尝试:

或者,如果它是一个小文本文件,您可以将其完全放入内存:

for items in text_file.read().split('\n'):

对文件对象(在for循环中隐式执行)调用readline时,它会保留结尾的“\n”和/或“\r”字符。在这种情况下,indprice变量仍然包含尾随的“\n”

尝试:

或者,如果它是一个小文本文件,您可以将其完全放入内存:

for items in text_file.read().split('\n'):

您的终端可能正在包装行吗?文件中的行确实包含
\n
,python不会剥离最后的
\n
,也不会
拆分(',')
删除除分隔符以外的任何内容,因此
indprice
在末尾包含新行。为了验证,您可以
打印(repr(indprice))
。您将看到换行符。您的终端可能正在包装该行吗?文件中的行确实包含
\n
,python不会剥离最后的
\n
,也不会
拆分(',')
删除除分隔符以外的任何内容,因此
indprice
在末尾包含一个换行符。为了验证,您可以
打印(repr(indprice))
。你会看到新线的。
for items in text_file.read().split('\n'):