在 Python 中,将 int、float 或 unicode 转换为字符串的单一、紧凑的方法是什么?

In Python, what would be a single, compact method to convert an int, a float or unicode to a string?

我有大量来自 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)

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

在 C 中你会调用

const unsigned char sqlite3_column_text(sqlite3_stmt, int iCol);

这将 return 将任何内容转换为文本

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

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

对数值调用unicode()

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