繁体   English   中英

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

[英]Remove newline/empty characters in Python string

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

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

但我不断在输出中获得换行符。

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

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

当我print list我得到了

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

我的目标是获得

output1
output2
output3

代替

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

我推荐你的情况:

if str.strip():
    print str

代替

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

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

这是应用De-Morgan's Theorm的一个有趣案例。

您想要打印不是'或\\ n的字符串。

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

因此,在否定上述陈述的同时,您将不得不应用de morgan的理论。

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

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

如果我正确地理解了你的问题,那么你正在寻找类似的东西:

from string import whitespace

l = ['output1', ' ', 'output2', 'output3', '\n', '', '','']
print('\n'.join(c for c in l if c not in whitespace))

输出:

output1
output2
output3

顺便说一句:我想比较字符串,使用==运算符。 is运算符比较对象的id 来自文档:

is运营商:

'is'运算符比较两个对象的身份 ; id()函数返回一个表示其身份的整数。

对象的id

对象的“身份” 这是一个整数,在该生命周期内保证该对象是唯一且恒定的。 具有非重叠生存期的两个对象可以具有相同的id()值。

''False ,所以可以这样做:

>>> mylist = ['output1', '', 'output2', 'output3', '', '', '', '', '\n']
>>> [i for i in mylist if i and i != '\n']
['output1', 'output2', 'output3']

或者,单独打印每个:

>>> for i in mylist:
...     if i and i != '\n':
...             print i
... 
output1
output2
output3

要删除所有可以使用的空字符:

>>> ll=['1','',''] 
>>> filter(None, ll) 
output : ['1']

请试试这个:

>>> l=['1','']
>>> l.remove('')
>>> l
['1']

或试试这个它将删除字符串中的所有特殊字符。

>>>import re
>>> text = "When asked about      Modi's possible announcement as BJP's election campaign committee head, she said that she cannot conf
irm or deny the development."
>>> re.sub(r'\W+', ' ', text)
'When asked about Modi s possible announcement as BJP s election campaign committee head she said that she cannot confirm or deny the d
evelopment '

1)表达式str is not '' or str is not '\\n' ,不能满足你的目的,因为它在str不等于''或者当str不等于''时打印str
假设str='' ,表达式归结为if False or True ,这将导致True

2)不建议使用liststr作为变量名,因为它们是python的本机数据类型

3) is可能的工作,但比较对象不是它的价值认同

因此,使用!=而不是使用is随着and运营商

 if str!='' and str!='\n':
       print str

产量

output1
output2
output3

实际上,只是分裂将起作用

os.popen(command_arg).read().split()

用“和”而不是“或”

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

暂无
暂无

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

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