繁体   English   中英

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

[英]Python: How to remove \n from a list element 2D?

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

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

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

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

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)

对于后一行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM