简体   繁体   中英

Octal to Decimal with (string) inputs in Python

Am stuck with some code. Am trying to write a function to translate octal to decimal accepting a string containing octal data (either a single number or a sequence of numbers separated by spaces) using loops and logic to return a string that contains one or more decimal numbers separated by spaces.

So far I have:

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)

Produces an error. Any ideas?

int takes an optional second argument (which defaults to 10): the base of the number to convert from. IIUC, you could just use:

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

Explanation in code's comments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM