如何在python中将数据放在单独的行上

如何在python中将数据放在单独的行上,python,lines,Python,Lines,这是我的代码: if mode == "1" and classname == "1": f = sorted(open("alphabetical test.txt").readlines()) print(f) 每次打印文件中的数据时,它都会这样打印: ['A, 9, 6, 2\n', 'K, 10, 1, 2\n', 'M, 5, 3, 7\n', 'P, 3, 5, 9\n'] 如何删除“\n”以及如何将它们放在单独的行中 谢谢。要

这是我的代码:

 if mode == "1" and classname == "1":
            f = sorted(open("alphabetical test.txt").readlines())
             print(f)
每次打印文件中的数据时,它都会这样打印:

['A, 9, 6, 2\n', 'K, 10, 1, 2\n', 'M, 5, 3, 7\n', 'P, 3, 5, 9\n']
如何删除“\n”以及如何将它们放在单独的行中


谢谢。

要从字符串中删除空格和换行符,可以使用或其变体 和。至于一台漂亮的打印机,有两种选择

例如:

if mode == "1" and classname == "1":
    # use context manager to open (and close) file
    with open("alphabetical test.txt") as handle:
        # iterate over each sorted line in the file
        for line in sorted(handle):
            # print the line, but remove any whitespace before
            print(line.rstrip())
只需在文件的每一行上调用.strip():

f = sorted([line.strip() for line in open("alphabetical test.txt").readlines()])
换衣服

print(f)

string
'.join()
方法获取一个字符串列表(或其他iterable),并将它们合并成一个大字符串。您可以在子字符串之间使用任何您喜欢的分隔符,例如
'-'。join(f)
将在每个子字符串之间放置
-


字符串列表中的
\n
是换行符的转义序列。因此,当您打印通过加入字符串列表而生成的大字符串时,列表中的每个原始字符串都将打印在单独的一行上。

这是什么意思“把它们放在不同的线上?您已经生成了一个列表
f
,其中包含您输入的已排序行;您现在如何处理该列表取决于您:)另外,请修复您的缩进,这都是错误的:
print(f)
不能缩进
f=..
下的一个空格。打印数据时,我希望它们在单独的行上,一行接另一行。如果要在单独的行上输出,为什么要删除换行符?非常感谢。现在工作很好:)我的荣幸,@MilanLad!如果你喜欢我的答案,请告诉我。:)
rstrip
可能会更好
print(''.join(f))