在 cython 中将 int 转换为 str?

Casting int to str in cython?

我有一个非常简单的问题,关于如何在 Cython 中将 int 转换为 string。我希望将一个可变数字连接到一个短语,例如

cdef str consPhrase = "attempt"
cdef int number = 7     #variable
cdef str newString = consPhrase + <str>number    #so it should be "attempt7", "attempt8", etc.

但是,我一直收到错误声明

TypeError: Expected str, got int

我查看了如何在 Cython 中进行转换,它声称它是 < > 括号,那么为什么不将 int 转换为 str?

我什至试过了

cdef str makeStr(str l):
    return l


cdef str consPhrase = "attempt"
cdef int number = 7
cdef str newString = consPhrase + makeStr(number)

但它在同一行(cdef str newString = consPhrase + makeStr(number) 行)抛出相同的错误。那么,完成这个简单任务的最有效和正确的方法是什么?如有任何帮助,我们将不胜感激!

最简单的方法就是将数据转换为字符串,就像您在任何其他 python 代码中所做的那样:

cdef str newString = consPhrase + str(number)

像您尝试那样进行转换是行不通的,因为 str 是一种 Python 类型,它映射到 Python2 和 [=13= 中的 bytes ] 在 Python3。由于它可能是一个 unicode 字符串,因此没有安全的方法可以像您尝试的那样将整数转换为字符串。