【问题标题】:In Python, what would be a single, compact method to convert an int, a float or unicode to a string?在 Python 中,将 int、float 或 unicode 转换为字符串的单一紧凑方法是什么?
【发布时间】:2017-06-21 00:12:34
【问题描述】:

我有大量来自 SQLite3 的数据库对象要循环并打印到终端。我试图有一个健壮的方法,可以应用于从数据库中检索的每个对象,以便将其转换为字符串。对象可能是字符串、整数、浮点数和 unicode。

我最初的方法是在每个对象上简单地使用函数str(),但这在某些 unicode 上失败了。然后我被提示尝试在每个对象上使用.encode("utf-8"),但这在整数('int' object has no attribute 'encode')上失败。尝试将这些对象转换为字符串的紧凑方法是什么?

我现在最好的情况如下:

try:
    string_representation = str(row[column])
except:
    string_representation = str(row[column].encode("utf-8"))
row_contents.append(string_representation)

有没有更好的,也许更紧凑的方法?单线就好了。

【问题讨论】:

  • @ravenspoint 我正在使用dataset 与 SQLite3 数据库进行交互,但我认为这并不特别重要;我已经从数据库中检索了对象,并且正在尝试将它们转换为字符串。

标签: python string utf-8 int encode


【解决方案1】:

在数值上调用unicode()

但是,如果您有一个包含 unicode 字符串和字节字符串的集合,并且您希望避免任何隐式编码,则必须检查类型。

【讨论】:

    【解决方案2】:

    在 C 中你会调用

    const unsigned char sqlite3_column_text(sqlite3_stmt, int iCol);

    这将返回任何转换为​​文本的内容

    https://www.sqlite.org/c3ref/column_blob.html

    不知道你会在 python 中做什么 - 最好使用数据库引擎来处理这些事情 = 更快、更可靠。

    【讨论】:

      猜你喜欢
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多