I'm not sure how to handle the input data that you have because that is not correctly formatted Python. However, I think there are a couple of ways to solve the problem.
Input data (as correct Python)
column = [
['\n "Hello" \n'],
['\n "Hello"', '\n "Hi"\n'],
['\n "Hello"',' \n "Hi"\n', '\n ""\n'],
['\n ""\n', '\n "Hello"', '\n "Hi"\n'],
['\n "Hello" \n', '\n ""\n'],
['\n ""\n', '\n "Hello" \n']
]
Code: First map
then List Comprehension
The map
removes the whitespace including the newline \n
characters. The list comprehension then removes the empty entries from each row (""
).
def stripper(text):
return text.strip().strip('"')
for row in column:
output = list(map(stripper, row))
print([i for i in output if i])
Output
['Hello']
['Hello', 'Hi']
['Hello', 'Hi']
['Hello', 'Hi']
['Hello']
['Hello']
Note that the end result has single quotes rather than double quotes. Let me know if this matters for what you're doing.
For fun
Just for fun, I took your input data absolutely literally, and wrote a set of replacements to result in exactly the output you have in the question.
Input data
column = r"""[\n "Hello" \n]
[\n "Hello", \n "Hi"\n]
[\n "Hello", \n "Hi"\n, \n ""\n]
[\n ""\n, \n "Hello", \n "Hi"\n]
[\n "Hello" \n, \n ""\n]
[\n ""\n, \n "Hello" \n]""".splitlines()
Code
for row in column:
print(row.replace('\\n "', '"').replace('" \\n', '"').replace('""\\n, ', '').replace(', ""\\n', '').replace('"\\n', ''))
Output
["Hello"]
["Hello", "Hi]
["Hello", "Hi]
["Hello", "Hi]
["Hello"]
["Hello"]