[英]Most pythonic way to convert a string to a octal number
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.
由于os.chmod()需要一个八进制数,我需要将一个字符串转换为八进制数。 For example:
例如:
'000' ==> 0000 (or 0o000 for you python 3 folks)
'644' ==> 0644 (or 0o644)
'777' ==> 0777 (or 0o777)
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: 在第一次尝试创建从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)
Is there a simpler way to do this? 有更简单的方法吗?
Have you just tried specifying base 8 to int
: 你刚刚尝试将base 8指定为
int
:
num = int(your_str, 8)
Example: 例:
s = '644'
i = int(s, 8) # 420 decimal
print i == 0644 # True
Here is the soluation: 这是解决方案:
Turn octal string "777" to decimal number 511 将八进制字符串“777”转换为十进制数511
dec_num = int(oct_string, 8) # "777" -> 511
you worry about the os.chmod()? 你担心os.chmod()? Let's try!
我们试试吧!
os.chmod("file", 511) # it works! -rwxrwxrwx.
os.chmod("file", 0777) # it works! -rwxrwxrwx.
os.chmod("file", int("2777",8)) # it works! -rwxrwsrwx. the number is 1535!
it proves that the chmod can accept decimal
and decimal can used as octal
in python ! 它证明了chmod
can accept decimal
和decimal can used as octal
在python中decimal can used as octal
!
it is enough for the octal, because if you try 这对八进制来说已经足够了,因为如果你尝试的话
print dec_num == 0777 # True
Then get the decimal number 511 translate to octal string
"0777" 然后得到十进制数511转换为八进制
string
“0777”
oct_num = oct(dec_num) # 511 -> "0777" , it is string again.
Pay attention there is no number 0777 but only oct string "0777" or dec num in the python if you write number 0777, it auto translate 0777 to 511, in the process there is no 0777 number exist. 注意没有数字0777但只有oct字符串“0777”或python中的dec num如果你写了数字0777,它自动翻译0777到511,在这个过程中没有0777数字存在。
summary 摘要
dec_num = int(oct_string, 8)
oct_num = oct(int(oct_string,8))
print dec_num # 511
print dec_num == 0777 # True ! It is actually 511, just like dec_num == 511
print oct_num # 0777
print oct_num == 0777 # Flase! Because it is a string!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.