Home >Backend Development >Python Tutorial >How Can I Efficiently Convert Integers to Strings in Any Base in Python?

How Can I Efficiently Convert Integers to Strings in Any Base in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 06:10:18366browse

How Can I Efficiently Convert Integers to Strings in Any Base in Python?

Converting Integers to Strings in Any Base

In Python, the int() function effortlessly creates an integer from a string with a specified base. However, the inverse operation of converting an integer to a string can be tricky. We aim to develop a general solution, int2base(num, base), that fulfills the condition:

int(int2base(x, b), b) == x

Here's a surprisingly simple solution that handles arbitrary bases:

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

This function converts a number n to base b and returns a list of digits. To convert a large number to base 577, for instance:

numberToBase(67854 ** 15 - 102, 577)

It will give you the correct result as a list:

[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]

Why This Solution Works

The provided solution demonstrates that sometimes, custom functions are necessary when built-in functions lack desired functionality. Here, int2base() overcomes limitations by:

  • Handling arbitrary bases from 2 to infinity.
  • Returning a list of digits rather than a string, as no built-in function exists for direct base conversion to any arbitrary base.

The above is the detailed content of How Can I Efficiently Convert Integers to Strings in Any Base in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn