簡體   English   中英

Python 中的(字符串)輸入的八進制到十進制

[英]Octal to Decimal with (string) inputs in Python

我被一些代碼困住了。 我正在嘗試編寫一個 function 將八進制轉換為十進制,接受包含八進制數據(單個數字或由空格分隔的數字序列)的字符串,使用循環和邏輯返回包含一個或多個由空格分隔的十進制數字的字符串。

到目前為止,我有:

def decode(code):
  decimal = 0
  code = code.split(" ")
  l = len(code) 
  for i in range (l):
    octal = len(i)
    for x in range (octal):
      digit_position = x - 1
      decimal += pow(8, digit_position) * int(x)
result = str(decimal)

產生錯誤。 有任何想法嗎?

int接受一個可選的第二個參數(默認為 10):要轉換的數字的基數。 IIUC,您可以使用:

def decode(code):
    return str(int(code, 8)).replace("", " ")

代碼注釋中的解釋:

def decode(code):
    code = code.split(' ')  # list of elements to convert
    code = [str(int(num, 8)) for num in code]  # convert using builtin int with second parameter - base
    return ' '.join(code)  # Return converted values as string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM