問題:
Python allows easy creation of an integer from a string of a given base via Python 允許通過給定基數的字符串輕鬆創建整數
int(str, base).
I want to perform the inverse: creation of a string from an integer , ie I want some function int2base(num, base)
, such that:我想執行相反的操作:從整數創建一個字符串,即我想要一些函數int2base(num, base)
,這樣:
int(int2base(x, b), b) == x
The function name/argument order is unimportant.函數名稱/參數順序並不重要。
For any number x
and base b
that int()
will accept.對於int()
將接受的任何數字x
和基數b
。
This is an easy function to write: in fact it's easier than describing it in this question.這是一個易於編寫的函數:實際上它比在這個問題中描述它更容易。 However, I feel like I must be missing something.但是,我覺得我一定錯過了一些東西。
I know about the functions bin
, oct
, hex
, but I cannot use them for a few reasons:我知道函數bin
、 oct
、 hex
,但由於以下幾個原因我不能使用它們:
Those functions are not available on older versions of Python, with which I need compatibility with (2.2)這些函數在舊版本的 Python 上不可用,我需要與 (2.2) 兼容
I want a general solution that can be called the same way for different bases我想要一個通用的解決方案,可以爲不同的基礎以相同的方式調用
I want to allow bases other than 2, 8, 16我想允許 2、8、16 以外的基數
Related有關的
- Python elegant inverse function of int(string, base) Python 優雅的 int(string, base) 反函數
- Integer to base-x system using recursion in python 在python中使用遞歸將整數轉換爲base-x系統
- Base 62 conversion in Python Python 中的 Base 62 轉換
- How to convert an integer to the shortest url-safe string in Python? 如何將整數轉換爲 Python 中最短的 url 安全字符串?
解決方案:
參考一: https://stackoom.com/question/9VqM參考二: How to convert an integer to a string in any base?