[英]Python: How to remove \n from a list element 2D?
I have a problem, in a 2D list: 我有一个问题,在2D列表中:
t = [['\n'], ['1', '1', '1', '1\n']]
I want to remove the "\\n"
from the nested lists. 我想从嵌套列表中删除
"\\n"
。
You can strip all strings in the nested lists: 您可以删除嵌套列表中的所有字符串:
t = [[s.strip() for s in nested] for nested in t]
This would remove all whitespace (spaces, tabs, newlines, etc.) from the start and end of each string. 这将从每个字符串的开头和结尾删除所有空格(空格,制表符,换行符等)。
Use str.rstrip('\\n')
if you need to be more precise: 如果您需要更精确,请使用
str.rstrip('\\n')
:
t = [[s.rstrip('\n') for s in nested] for nested in t]
If you need to remove empty values too, you may have to filter twice: 如果您还需要删除空值,则可能需要过滤两次:
t = [[s.rstrip('\n') for s in nested if not s.isspace()] for nested in t]
t = [nested for nested in t if nested]
where the first line only includes a stripped string if it contains more than just whitespace, and the second loop removes entirely empty lists. 其中第一行只包含一个剥离的字符串,如果它包含的不仅仅是空格,第二个循环删除完全空的列表。 In Python 2, you could also use:
在Python 2中,您还可以使用:
t = filter(None, nested)
for the latter line. 对于后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.