删除Python字符串中的换行符/空字符

2024-09-28 22:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,这听起来可能重复了,但我已经尝试了所有的可能性,比如str.strip()str.rstrip()str.splitline(), 另外,如果还有,请检查如下:

if str is not '' or str is not '\n':
    print str

但我总是在输出中添加新行。

我正在存储os.popen的结果:

list.append(os.popen(command_arg).read())

当我这样做的时候

['output1', '', 'output2', 'output3', '', '', '','']

我的目标是

output1
output2
output3

而不是

    output1
  <blank line>
    output2
    output3
 <blank line>    
 <blank line>

Tags: ifisoslinenot可能性strippopen
3条回答

我建议你的案子:

if str.strip():
    print str

而不是

if str is not '' or str is not '\n':
    print str

重要提示:测试字符串相等性必须使用s == "..."而不是使用s is "..."

这是应用德摩根理论的一个有趣的例子。

您要打印不是“”或\n的字符串

也就是说,if str=='' or str =='\n', then don't print.

因此,在否定上述说法的同时,你必须应用德摩根的理论。

所以,您必须使用if str !='' and str != '\n' then print

filter(str.strip, ['output1', '', 'output2', 'output3', '', '', '',''])

相关问题 更多 >