Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's actually happening when I convert an int to a string?

Tags:

python

I understand it's easy to convert an int to a string by using the built-in method str(). However, what's actually happening? I understand it may point to the __str__ method of the int object but how does it then compute the “informal” string representation? Tried looking at the source and didn't find a lead; any help appreciated.

like image 446
Jester Jeffrey Avatar asked Jan 28 '14 23:01

Jester Jeffrey


People also ask

What happens when an int is added to a string?

Just add to int or Integer an empty string "" and you'll get your int as a String. It happens because adding int and String gives you a new String.

Can you change an integer to a string?

Method 1: Using toString Method of Integer Class The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved.

What happens if you int a string Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

What function converts strings to integers?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.


2 Answers

Python repeatedly divides the int by 10 and uses % 10 to get the decimal digits one by one.

Just to make sure we're looking at the right code, here's the function Python 2.7 uses to convert ints to strings:

static PyObject *
int_to_decimal_string(PyIntObject *v) {
    char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
    long n = v->ob_ival;
    unsigned long absn;
    p = bufend = buf + sizeof(buf);
    absn = n < 0 ? 0UL - n : n;
    do {
        *--p = '0' + (char)(absn % 10);
        absn /= 10;
    } while (absn);
    if (n < 0)
        *--p = '-';
    return PyString_FromStringAndSize(p, bufend - p);
}

This allocates enough space to store the characters of the string, then fills the digits in one by one, starting at the end. When it's done with the digits, it sticks a - sign on the front if the number is negative and constructs a Python string object from the characters. Translating that into Python, we get the following:

def int_to_decimal_string(n):
    chars = [None] * enough # enough room for any int's string representation
    abs_n = abs(n)
    i = 0
    while True:
        i += 1
        chars[-i] = str(abs_n % 10) # chr(ord('0') + abs_n % 10) is more accurate
        abs_n //= 10
        if not abs_n:
            break
    if n < 0:
        i += 1
        chars[-i] = '-'
    return ''.join(chars[-i:])
like image 96
user2357112 supports Monica Avatar answered Sep 19 '22 08:09

user2357112 supports Monica


Internally the Int object is stored as 2's complement representation like in C (well, this is true if range value allow it, python can automagically convert it to some other representation if it does not fit any more).

Now to get the string representation you have to change that to a string (and a string merely some unmutable list of chars). The algorithm is simple mathematical computing: divide the number by 10 (integer division) and keep the remainder, add that to character code '0'. You get the unit digit. Go on with the result of the division until the result of the division is zero. It's as simple as that.

This approach works with any integer representation but of course it will be more efficient to call the ltoa C library function or equivalent C code to do that if possible than code it in python.

like image 38
kriss Avatar answered Sep 20 '22 08:09

kriss