简体   繁体   中英

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

I have a problem, in a 2D list:

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

I want to remove the "\\n" from the nested lists.

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:

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:

t = filter(None, nested)

for the latter line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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