python string strip没有条带化换行符

时间:2014-06-13 01:10:56

标签: python strip

我无法删除空格和换行符。知道可能出了什么问题吗?

    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'
' '

3 个答案:

答案 0 :(得分: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 :(得分:1)

如果fline是一个字符串,那么使用它作为参数调用repr会将其括在文字引号中。因此:

foo\n

变为

"foo\n"

由于换行符不在字符串的末尾,strip不会将其删除。也许可以考虑不要在{<1}}打电话repr之前打电话给strip,或者在打电话给{{1}}之后再打电话给

答案 2 :(得分:1)

从其他人提到的,只需改变

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

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

请注意,您可能需要.rstrip()甚至.rstrip("\n")