我希望通过存储在配置文件中的文件掩码来更改文件的权限。由于 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/