[英]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.
我正在尝试编写一个 function 将八进制转换为十进制,接受包含八进制数据(单个数字或由空格分隔的数字序列)的字符串,使用循环和逻辑返回包含一个或多个由空格分隔的十进制数字的字符串。
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. int
接受一个可选的第二个参数(默认为 10):要转换的数字的基数。 IIUC, you could just use: IIUC,您可以使用:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.