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

时间:2015-02-15 12:00:35

标签: 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'以及如何将它们分开放置?

感谢。

3 个答案:

答案 0 :(得分:4)

更改您的

print(f)

print(''.join(f))

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

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

答案 1 :(得分:2)

只需在文件的每一行调用.strip():

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

答案 2 :(得分:1)

要从字符串中删除空格和换行符,可以使用str.strip或其变体 分别为str.lstripstr.rstrip。至于漂亮的打印机,有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())