将字符串转换为八进制数的最pythonic方法 [英] Most pythonic way to convert a string to a octal number

查看:116
本文介绍了将字符串转换为八进制数的最pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to change permissions on a file with the file mask stored in a configuration file. Since os.chmod() requires an octal number, I need to convert a string to an octal number. For example:

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

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

After an obvious first attempt of creating every octal number from 0000 to 0777 and putting it in a dictionary lining it up with the string version, I came up with the following:

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)

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

Is there a simpler way to do this?

推荐答案

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

Have you just tried specifying base 8 to int:

num = int(your_str, 8)

示例:

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

这篇关于将字符串转换为八进制数的最pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆