简体   繁体   English

Python 从嵌套列表中删除换行符

[英]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"?我将如何遍历列表并删除“\\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", "")

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

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