本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
oct(x)
-
x:整数(int)。如果 x 不是一个 Python int 对象,它必须定义一个返回整数的 __index__() 方法。
返回值:
另外,如何希望输出的字符串不包含八进制默认的“0o”前缀,可以通过以下两种方式实现:
-
使用format()函数:
可以通过不同的格式化选项来控制输出。例如,format(42, ‘#o’)会返回‘0o52’,包含了前缀“0o”;而format(42, ‘o’)则仅返回’52’,不包含前缀。
-
格式化字符串字面量(f-string):
它允许直接在字符串中嵌入表达式。例如,f'{42:#o}’会产生带有“0o”前缀的字符串‘0o52’,而f'{42:o}’则会生成不带前缀的字符串’52’。
下面是一些使用 oct() 函数的示例:
-
示例 1:基本使用
# 转换正整数
print(oct(42))
# 输出: '0o52'
# 转换零
print(oct(0))
# 输出: '0o0'
# 转换负整数
print(oct(-42))
# 输出: '-0o52'
# 处理字符串或浮点数类型会引发 TypeError
try:
print(oct("4.2"))
except TypeError as e:
print(e)
# 输出: 'str' object cannot be interpreted as an integer
-
示例 2:使用format()函数或f-string
format(42, '#o'), format(42, 'o')
# 输出: ('0o52', '52')
f'{42:#o}', f'{42:o}'
# 输出: ('0o52', '52')
-
示例 3:具有 __index__() 方法的对象
class MyClass:
def __index__(self):
return 456
obj = MyClass()
result = oct(obj)
print(result)
# 输出:0o710,即整数456的八进制字符串


本篇文章来源于微信公众号: 码农设计师