如何将数据放在 python 中的不同行

How to put data on separate lines in python

这是我的代码:

 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”以及如何将它们放在不同的行中?

谢谢。

要从字符串中删除空格和换行符,您可以使用 str.strip 或其变体 str.lstrip and str.rstrip, respectively. As for a pretty printer, there's pprint.

一个例子:

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)

print(''.join(f))

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

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