python - 将字符串转换为八进制数的最pythonic方式

标签 python python-2.6

我希望通过存储在配置文件中的文件掩码来更改文件的权限。由于 os.chmod() 需要八进制数,因此我需要将字符串转换为八进制数。例如:

'000' ==> 0000 (or 0o000 for you python 3 folks)
'644' ==> 0644 (or 0o644)
'777' ==> 0777 (or 0o777)   

在第一次尝试创建从 0000 到 0777 的每个八进制数并将其放入字典中并将其与字符串版本对齐后,我想出了以下内容:

def new_oct(octal_string):

    if re.match('^[0-7]+$', octal_string) is None:
        raise SyntaxError(octal_string)

    power = 0
    base_ten_sum = 0

    for digit_string in octal_string[::-1]:
        base_ten_digit_value = int(digit_string) * (8 ** power)
        base_ten_sum += base_ten_digit_value
        power += 1

    return oct(base_ten_sum)

有没有更简单的方法来做到这一点?

最佳答案

您是否刚刚尝试将基数 8 指定为 int:

num = int(your_str, 8)

例子:

s = '644'
i = int(s, 8) # 420 decimal
print i == 0644 # True #Python 2.x

对于 Python 3.x 做

. . .
print(i == 0o644)

关于python - 将字符串转换为八进制数的最pythonic方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18806772/

相关文章:

python - pip 列出了错误安装的软件包版本?

python - 将args线程化到给定错误的许多参数?

python - Django 保存后无法登录

Python 3、Numpy : Split data into blocks of fixed length and calculate statistics for each block

python - 将消息放入azure队列

python - 在 Python 中一次遍历 2 个列表

Python 对多个级别的列表列表进行排序并具有自定义顺序

python - 在 OS X 10.6.8 上安装 numpy 的问题

python - 令人难以置信的 Python boolean 特性

python - 导入模块时到底会发生什么?