Python:如何从列表元素2D中删除\ n?

时间:2013-12-19 11:11:00

标签: python python-2.7

我有一个问题,在2D列表中:

t = [['\n'], ['1', '1', '1', '1\n']]

我想从嵌套列表中删除"\n"

1 个答案:

答案 0 :(得分:3)

您可以删除嵌套列表中的所有字符串:

t = [[s.strip() for s in nested] for nested in t]

这将从每个字符串的开头和结尾删除所有空格(空格,制表符,换行符等)。

如果您需要更精确,请使用str.rstrip('\n')

t = [[s.rstrip('\n') for s in nested] for nested in t]

如果您还需要删除值,则可能需要过滤两次:

t = [[s.rstrip('\n') for s in nested if not s.isspace()] for nested in t]
t = [nested for nested in t if nested]

其中第一行只包含一个剥离的字符串,如果它包含的不仅仅是空格,第二行将删除完全空的列表。在Python 2中,您还可以使用:

t = filter(None, nested)

用于后一行。