Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *