Remove newline/empty characters in Python string
10,103
Solution 1
I'd recommend for your case:
if str.strip():
print str
instead of
if str is not '' or str is not '\n':
print str
Important: Testing for string equality must be done using s == "..."
rather than with s is "..."
.
Solution 2
This is an interesting case for applying the De-Morgan's Theorm.
You want to print strings that are not '' or \n.
That is,if str=='' or str =='\n', then don't print.
Hence while negating the above statement,You will have to apply the de morgan's theorm.
So,You will have to use if str !='' and str != '\n' then print
Solution 3
filter(str.strip, ['output1', '', 'output2', 'output3', '', '', '',''])
![rocx](https://i.stack.imgur.com/w5q01.jpg?s=256&g=1)
Author by
rocx
Updated on June 04, 2022Comments
-
rocx about 2 years
Well, this may sound repeat, but I've tried all possibilities like
str.strip()
,str.rstrip()
,str.splitline()
, also if-else check like:if str is not '' or str is not '\n': print str
But I keep getting newlines in my output.
I'm storing the result of os.popen:
list.append(os.popen(command_arg).read())
When I do
print list
I get['output1', '', 'output2', 'output3', '', '', '','']
My aim is to get
output1 output2 output3
instead of
output1 <blank line> output2 output3 <blank line> <blank line>
-
Johannes Charra about 11 yearsGood point. :) Still, comparing strings with
is
is error-prone. Consider:a = "abc\n"; b = a[-1:]; print b is "\n"
-
aldeb about 11 years
l.remove('')
will only remove the first''
in the list. I think the OP wants to remove all of them -
Vaibhav Jain about 11 yearsThen try this :` >>> ll=['1','',''] >>> filter(None, ll) ['1']`
-
volcano almost 10 yearsYou've beat me to that :)
-
volcano almost 10 yearssimply s not in (' ', '\n) will work (and str is class name in Python)