2010-01-23 57 views
10

把我的頭髮拉出來......在過去的一個小時裏一直在玩這個,但我無法得到它做我想要的,即。刪除換行符序列。rstrip不刪除換行符我在做什麼錯?

def add_quotes(fpath): 

     ifile = open(fpath, 'r') 
     ofile = open('ofile.txt', 'w') 

     for line in ifile: 
      if line == '\n': 
       ofile.write("\n\n") 
      elif len(line) > 1: 
       line.rstrip('\n') 
       convertedline = "\"" + line + "\", " 
       ofile.write(convertedline) 

     ifile.close() 
     ofile.close() 

回答

17

線索在rstrip的簽名。

它返回字符串的副本,但與所需的字符剝離,因此你需要指定line新值:

line = line.rstrip('\n') 

這使得操作有時是非常方便的鏈接:

"a string".strip().upper() 

由於Max. S在評論中說,Python字符串是不可變的,這意味着任何「變異」操作都會產生變異副本。

這就是它在許多框架和語言中的工作原理。如果你真的需要一個可變的字符串類型(通常出於性能原因),那麼就有字符串緩衝區類。

+6

更一般地說,Python中的字符串是不可變的。一旦創建,它們就不能改變。任何對字符串做某事的函數都會返回一個副本。 – 2010-01-23 02:37:14

+0

確實。也許我應該把它放在答案中。 – Skurmedel 2010-01-23 02:38:45

+0

謝謝,我是新的,它必須是簡單的,...我自己的錯誤只是通過python文檔瀏覽。 – volting 2010-01-23 02:44:08

3

,你可以做這樣的

def add_quotes(fpath): 
     ifile = open(fpath, 'r') 
     ofile = open('ofile.txt', 'w') 
     for line in ifile: 
      line=line.rstrip() 
      convertedline = '"' + line + '", ' 
      ofile.write(convertedline + "\n") 
     ifile.close() 
     ofile.close() 
2

正如Skurmedel的回答和評論提到,你需要做的是這樣的:

stripped_line = line.rstrip() 

,然後寫出來stripped_line。