Menu Close

How to convert an integer to a string in any base with Python?

Sometimes, we want to convert an integer to a string in any base with Python.

In this article, we’ll look at how to convert an integer to a string in any base with Python.

How to convert an integer to a string in any base with Python?

To convert an integer to a string in any base with Python, we can create our function.

For instance, we write

def number_to_base(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

to create the number_to_base function.

In it, we have a while loop that keeps append the remaining when dividing a by b converted to an int into the digits list.

And then we divide n by b, round it to an int, and assign the result to b

Once n is 0, we return a copy of the digits` list.

Conclusion

To convert an integer to a string in any base with Python, we can create our function.

Posted in Python, Python Answers