美文网首页
python列表写入文本时将u'hello'转化为"hello"

python列表写入文本时将u'hello'转化为"hello"

作者: analanxingde | 来源:发表于2019-04-03 16:47 被阅读0次

该问题需要转化原因:

编码格式不同,提示当前是utf-8编码的字符串

解决方式

我使用的是暴力替换的方式

def covert():
    File = 'covert.txt'
    for line in fileinput.input(File, inplace=1):
        line = line.replace('\'', '\"')
        line=line.replace('u','')
        print line

比较科学的方式:按照相应的编码格式解编码,utf8string ==unicodestring.encode("utf-8")即可。
常见的四种编码格式解编,和编码方式与python字符串之间的转换方式如下:

unicodestring = u"Hello world"
# 将Unicode转化为普通Python字符串:"encode"
utf8string = unicodestring.encode("utf-8")
asciistring = unicodestring.encode("ascii")
isostring = unicodestring.encode("ISO-8859-1")
utf16string = unicodestring.encode("[utf-16](https://www.baidu.com/s?wd=utf-16&tn=SE_PcZhidaonwhc_ngpagmjz&rsv_dl=gh_pc_zhidao)")

编码为相应的形式:

# 将普通Python字符串转化为Unicode:"decode"
plainstring1 = unicode(utf8string, "utf-8")
plainstring2 = unicode(asciistring, "ascii")
plainstring3 = unicode(isostring, "ISO-8859-1")
plainstring4 = unicode(utf16string, "utf-16")

相关文章

  • python列表写入文本时将u'hello'转化为"hello"

    该问题需要转化原因: 编码格式不同,提示当前是utf-8编码的字符串 解决方式 我使用的是暴力替换的方式 比较科学...

  • 熟悉Markdown语法

    大标题 Hello world 二级标题 三级标题 列表加粗 无序列表 文本1 文本2 文本3 有序列表 你好 你...

  • 字符串

    str.title():将每个单词的首字母改为大写,“hello word”→“Hello Word” str.u...

  • python 记录

    print("hello python interpreter") message = "hello python...

  • PAT A1031 Hello World for U

    PAT A1031 Hello World for U A1031 Hello World for U 题目 如何...

  • 列表和元组

    列表 list函数>>> list('hello') #用于将字符串创建为列表,['h','e','l',...

  • Python 基础

    以下文件均以hello.py命名 1、运行Python hello.py时,Python 文件必须要以.py结尾,...

  • python基础

    hello worldprint ("hello world) //python3.xprint "hello w...

  • ARM-第四次

    配置环境 将hello.c下载进开发板 不能运行,因为hello.c里面的头文件不适用与u-boot 在u-boo...

  • json 分隔符 编码方法

    print('hello,', world', 'hello', 'python', sep=',', end='...

网友评论

      本文标题:python列表写入文本时将u'hello'转化为"hello"

      本文链接:https://www.haomeiwen.com/subject/osmzbqtx.html