2012-11-05 72 views
0

我想從\n id int(10) NOT NULL開始的行刪除\n。我試過strip(),rstrip(),lstrip()replace('\n', '')。我不明白。我究竟做錯了什麼?Python:無法刪除 n

print(column) 
print(column.__class__) 
x = column.rstrip('\n') 
print(x) 
x = column.lstrip('\n') 
print(x)    
x = column.strip('\n')   
print(x) 
print(repr(column)) 

\n id int(10) NOT NULL 
<type 'str'> 
\n id int(10) NOT NULL 
\n id int(10) NOT NULL 
\n id int(10) NOT NULL 
\n id int(10) NOT NULL 
'\\n `id` int(10) NOT NULL' 
+6

Dunno。你爲什麼不展示一些實際的代碼? –

+4

源代碼或它沒有發生! ;) – sth

+0

..有三種可能性,'strip()','.rstrip()'和'.lstrip()',你只給出一個輸出,它不會去掉一個初始的'\ n '。你能顯示其他人的輸出嗎? (和'repr(專欄)'。) – DSM

回答

7

你肯定\n是換行,而不是字面\隨後文字n?在這種情況下,你會想:

s = r'\nthis is a string' 
s = s.strip() 
print s 
s = s.strip(r'\n') 
print s 

可能是一個更好的辦法是檢查它是否剝離之前\n開始,然後用切片:

if s.startswith(r'\n'): s = s[2:] 

甚至更​​有力,re.sub

re.sub(r'^(?:\\n)+','',r'\n\nfoobar') 

根據你上面描述的症狀,我幾乎肯定了這種情況。

+1

看起來你贏了這一輪!爲了撫慰我受傷的驕傲,我會指出's.strip(r'\ n')'有點危險,因爲它也會剝奪最初的'n's .. – DSM

+0

@DSM即使這似乎已經贏了我會保持你的身邊,因爲人們也可以很容易地解決你的問題。當你說你會刪除它時,我以爲你在開玩笑。 –

+0

非常感謝。你讓我今天一整天都感覺很好。 – OrangeTux