搜索
写经验 领红包

pytho中oct的用法(pythooctave)

导语:一日一技:Python中内置的oct() 函数

python中oct的用法(python octave)

oct()函数是Python3中的内置方法之一。 oct()方法采用整数,并以字符串格式返回其八进制表示形式。

oct()语法如下:

Syntax : oct(x) 参数x – Must be an integer number and can be in either binary, decimal or hexadecimal format.返回值的八进制表示形式。Errors and Exceptions :   TypeError:当将整数类型常量以外的任何内容作为参数传递时,返回TypeError。

代码#1:说明oct()函数的用法
print(&34; + oct(23)) print(&34;&39;z&34; + oct(ord(&39;))) print(&34;&34; + oct(0b10111)) print(&34;&34; + oct(0x17)) 

输出:

The octal representation of 23 is 0o27The octal representation of the ascii value of &39; is 0o172The octal representation of the binary of 23 is 0o27The octal representation of the binary of 23 is 0o27

代码2:展示TypeError异常错误
print(&34; + oct(29.5)) 

输出报错信息:

Traceback (most recent call last):  File &34;, line 3, in     print(&34;+oct(29.5))TypeError: &39; object cannot be interpreted as an integer

应用范围:

oct()用于所有类型的标准转换。 例如,从十进制转换为八进制,从二进制转换为八进制,从十六进制转换为八进制.

代码3:实例如下
print(&34;) print(&34;) print(&34;) def  bin_to_oct(): print(&34;) x = int(input(), 2) print(&34; + str(x) + &34; + oct(x) ) def hex_to_oct(): print(&34;) x = int(input(), 16) print(&34; + str(x) + &34; + oct(x)) def decimal_to_oct(): print(&34;) x = int(input()) print(&34; + str(x) + &34; + oct(x)) ch = input(&34;) if ch is &39;: hex_to_oct() elif ch is &39;: decimal_to_oct() elif ch is &39;: bin_to_oct() 

输出:

a. Hexadecimal to Octal b. Decimal to Octalc. Binary to OctalEnter your choice :-aEnter your input in HEX format :-0x13Octal form of 19 is 0o23
a. Hexadecimal to Octal b. Decimal to Octalc. Binary to OctalEnter your choice :-bEnter a number with base-10 format :-123Octal form of 123 is 0o173

本文内容由小梓整理编辑!