[英]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)不建議使用list
和str
作為變量名,因為它們是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.