简体   繁体   中英

Python remove newline from nested lists

How do you remove newline characters from nested lists?

[['Item 1', None, None],
 ['1',
  'Name',
  'Sample_data \nSamepleData'],
 ['2', 'Sample_data\n test', 'test']]

How would i iterate through the list and remove every instance of "\\n"?

for item in list:
    item.replace('\n', '')

You should look up the documentation before asking this kind of question.

That snippet should work:

def replace_newlines(obj):
    if isinstance(obj, list):
        return list(map(replace_newlines, obj))
    if obj:
        return obj.replace('\n', '')

given = [
    ['Item 1', None, None],
    ['1', 'Name', 'Sample_data \nSamepleData'], 
    ['2', 'Sample_data\n test', 'test']
]

result = replace_newlines(given)
    for x in range (0,len(list2[i])):
        for z in list2[x]:
            z.replace("\n", "")

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