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
Release: 2024-12-05 06:10:18
Original
355 people have browsed it

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
Copy after login

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]
Copy after login

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)
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template