catcoder7
catcoder7

Reputation: 21

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?

Upvotes: 1

Views: 196

Answers (2)

Karol Milewczyk
Karol Milewczyk

Reputation: 350

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

Upvotes: 0

The Thonnu
The Thonnu

Reputation: 3624

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("", " ")

Upvotes: 2

Related Questions