2013-05-10 89 views
1

當我嘗試在以下情況下使用strip()時,輸出有點不同。python strip()從文件中讀取行

for line in tagfile: 
    tag_name = line.strip("<>") 
    print tag_name 

輸出 strike>

,但如果我用下面的方法

tag_name = "<strike>" 
print tag_name.strip("<>") 

輸出 strike

如果誰可以幫助嗎?

回答

3

這是由於換行符的換行符,strip並沒有超出它,因爲您沒有將換行符指定爲令牌。試試這個:

for line in tagfile: 
    tag_name = line.strip("<>\n") 
    print tag_name 

或使用本:

for line in tagfile: 
    line = line.rstrip() 
    tag_name = line.strip("<>") 
    print tag_name 
+0

它的工作原理,但只有在「\ n」是旁邊的「>」,當它們之間的空間,它失敗。 – Vimos 2013-05-10 08:49:12

+0

好吧,line = line.rstrip()是個好主意。謝謝你們! – Vimos 2013-05-10 08:55:57