Python 中基本轉換的主要問題是它可能非常慢。
def convert_to_base(num, base): if base < 2 or (base > 10 and base != 16): print("Invalid Base") return -1 else: converted_string, mod = "", num % base while num != 0: mod = num % base num = int(num / base) converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string return converted_string
這是將數字轉換為給定基數的函數的函數定義。 如果基數小於 2 或大於 10 且不等於 16,它會打印一條錯誤消息。 否則,它計算數字和底數的模數,並將其存儲在變量“mod”中。 然後它進入一個 while 循環,繼續計算數字的模數和基數,直到數字等於 0。它將每個結果存儲在變量“converted_string”中。 最後,它返回字符串“converted_string”。
數據類型轉換
在 Python 中有幾種轉換數據類型的方法。 最簡單的方法是使用 type() 函數。 例如,要將數字轉換為字符串,可以使用以下代碼:
str = 類型(數字)
另一種方法是使用 str() 函數。 例如,要將字符串轉換為數字,可以使用以下代碼:
數字 = 海峽(字符串)