2014-06-13 79 views
0

我無法去掉空格和換行符。任何想法可能會出錯?python string strip not striping newline

line_count = 0 
    word_count = 0 

    for fline in fh: 
     line = repr(fline) 
     line = line.strip() 
     print line 
     line_count += 1 
     word_count += len(line.split()) 

    result['size'] = filesize 
    result['line'] = line_count 
    result['words'] = word_count 

輸出

'value of $input if it is\n' 
' larger than or equal to ygjhg\n' 
' that number. Otherwise assigns the value of \n' 
' \n' 
' ' 
+0

你爲什麼在這裏使用'repr'? –

回答

2

你的字符串是由因repr()雙引號括起來:

>>> x = 'hello\n' 
>>> repr(x) 
"'hello\\n'" 
>>> repr(x).strip() 
"'hello\\n'" 
>>> 

這裏是你編輯的代碼:

line_count = 0 
word_count = 0 

for fline in fh: 
    line = repr(line.strip()) 
    print line 
    line_count += 1 
    word_count += len(line.split()) 

result['size'] = filesize 
result['line'] = line_count 
result['words'] = word_count 
1

如果fline是一個字符串,然後再調用repr用它作爲參數將在字面引號括起來。因此:

foo\n 

成爲

"foo\n" 

由於新行是不是在串了年底,strip不會刪除它。也許考慮不要撥打repr,除非您急需,或撥打電話撥打strip

1

從什麼其他人所說的,只是改變

line = repr(fline) 
    line = line.strip() 

line = line.strip() 
    line = repr(fline) 

請注意,您可能需要.rstrip()甚至.rstrip("\n")來代替。