字符编码 - python把汉字字符串中的'\n‘去掉
大家讲道理
大家讲道理 2017-04-17 14:35:24
0
2
698

从文件中读出的一个汉字字符串
用这个句话判断是否包含回车:

python    if '\n' in mystring:
        print type(mystring)
        #<type 'unicode'>
        mystring.replace('\n', '')
        #does not work
        mystring.replace(u'\n', u'')
        #does not work
        mystring.encode("gbk")
        mystring.replace("\n", "")
        #does not work
        mystring.encode("utf-8")
        mystring.replace("\n", "")
        #does not work
        mystring.encode("ascii")
        mystring.replace("\n", "")
        #UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-20
        print mystring

这该如何是好?请指教!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
刘奇

What I think of is, since it is read from a file, why not use strip?

python    file = open('file.txt', 'rt')
    for line in file:
        line = line.strip()
小葫芦

The replace method of a string will not modify the content of the original string

Try

    a = "woshishazi\n!!!"
    a = a.replace('\n', '')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template