Reputation: 302
I have a very simple question on how to cast an int to string in Cython. I wish to concatenate a variable number to a phrase, e.g.
cdef str consPhrase = "attempt"
cdef int number = 7 #variable
cdef str newString = consPhrase + <str>number #so it should be "attempt7", "attempt8", etc.
However, I keep getting an error claiming
TypeError: Expected str, got int
I've looked on how to cast in Cython, and it claims that it is down with the < > brackets, so why isn't the int being converted into the str?
I've even tried
cdef str makeStr(str l):
return l
cdef str consPhrase = "attempt"
cdef int number = 7
cdef str newString = consPhrase + makeStr(number)
but it throws the same error on the same line (the cdef str newString = consPhrase + makeStr(number)
line). So, what is the most efficient and correct way of doing this simple task? Any help would be appreciated!
Upvotes: 2
Views: 2239
Reputation: 5590
The easiest way to do this is just to convert the data to a string, just like you would in any other python code:
cdef str newString = consPhrase + str(number)
Casting like you are trying to do won't work because str
is a Python type which maps to bytes
in Python2 and unicode
in Python3. Since it might be a unicode string, there's no safe way to cast an integer to a string like you're trying to do.
Upvotes: 3