python把汉字字符串中的'\n‘去掉

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

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

这该如何是好?请指教!

阅读 6.5k
2 个回答

我想到的是,既然是从文件读入的,那为什么不用strip呢?

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

字符串的 replace 方法不会修改原字符串的内容

尝试

    a = "woshishazi\n!!!"
    a = a.replace('\n', '')
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题