美文网首页
《笨办法学Python3》练习二十三:字符串,字节和字符编码

《笨办法学Python3》练习二十三:字符串,字节和字符编码

作者: 雨开Ame | 来源:发表于2019-03-05 07:57 被阅读0次

练习代码

import sys
script, encoding, errors = sys.argv

def main(language_file, encoding, errors):
    line = language_file.readline()
    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)

def print_line(line, encoding, errors):   
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors = errors)
    cooked_string = raw_bytes.decode(encoding, errors = errors)

    print(raw_bytes, "<===>", cooked_string)
languages_file = open("languages.txt", encoding = "utf-8")
main(languages_file, encoding, errors)

补充

  1. encodedecode互为逆操作,encode是将字符串中的字符都转化为encoding属性指定的编码,转化后的又叫raw string

  2. errors属性制定的是编码错误后的操作方式,有很多值:strict是报UnicodeError错误;ignore是忽略;replace是指替代正确部分。

相关文章

网友评论

      本文标题:《笨办法学Python3》练习二十三:字符串,字节和字符编码

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