Domanda

It is maybe a silly question but I'm trying to translate a javascript sentence to python and I can't find a way to convert an integer to string like javascript.

Here the javascript sentence:

var n = 11;
n = n.toString(16);

It returns 'b'.

I tried chr() in python but it is not the same. I don't know to program in javascript so I would be grateful if someone can help me to understand how does javascript convertion works to do that.

Thanks you.

È stato utile?

Soluzione

the line

n = n.toString(16);

Is converting the number 11 to a string base 16 or 0xB = 11 decimal.

you can read more about int.toString

the code you want is:

n = 11
n = format(n, 'x')

or

n = hex(n).lstrip('0x')

the lstrip will remove the 0x that is placed when converting to hex

Altri suggerimenti

Everything below was my original answer, didn't see it was base 16 instead of base 10. This is not the solution.

I wonder how much effort you took in searching for an answer: Converting integer to string in Python? was the first result when googling "python integer to string". Taking a look at the search result, this should do it:

n = 11
n = str(n)

This might work too:

n = 11
n.__str__()

You can give it a try here http://progzoo.net/wiki/Python:Convert_a_Number_to_a_String

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top