首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python中从未知类型转换为UTF-8?

在python中从未知类型转换为UTF-8?
EN

Stack Overflow用户
提问于 2014-01-12 03:22:49
回答 1查看 446关注 0票数 0

在这个比较函数中,我遇到了一些笨拙的代码:

代码语言:javascript
运行
复制
def compare(this, that, encoding="utf-8"):

      if type(this) == type(str()):
           this = this.encode(encoding)
      if type(this) == type(bytes()):
           this = this.decode().encode(encoding)

      if type(that) == type(str()):
           that = that.encode(encoding)
      if type(that) == type(bytes()):
           that = that.decode().encode(encoding)

      # there has to be a faster way...

      return this==that

目的是在进行比较之前确保thisthat在相同的编码中。但这似乎是一种尴尬的方式。有没有更简洁的方法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-12 11:15:46

我认为最简单的方法是将这两个输入转换为str并进行比较。

代码语言:javascript
运行
复制
def compare(this, that, encoding="utf-8"):
    // convert this to str
    if isinstance(this, bytes):
        this = str(this, encoding)
    // convert that to str
    if isinstance(that, bytes):
        that = str(that, encoding)
    return this == that
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21070922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档