字符编码 - python把汉字字符串中的'\n‘去掉
大家讲道理
大家讲道理 2017-04-17 14:35:24
[Python讨论组]

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

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

这该如何是好?请指教!

大家讲道理
大家讲道理

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

全部回复(2)
怪我咯

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

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

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

尝试

    a = "woshishazi\n!!!"
    a = a.replace('\n', '')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号