Most pythonic way to convert a string to a octal number

后端 未结 2 684
我寻月下人不归
我寻月下人不归 2020-12-20 11:47

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 o

相关标签:
2条回答
  • 2020-12-20 12:28

    Have you just tried specifying base 8 to int:

    num = int(your_str, 8)
    

    Example:

    s = '644'
    i = int(s, 8) # 420 decimal
    print i == 0644 # True
    
    0 讨论(0)
  • 2020-12-20 12:30

    Here is the soluation:

    Turn octal string "777" to decimal number 511

    dec_num = int(oct_string, 8) # "777" -> 511
    

    you worry about the 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 !


    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"

    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.

    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!
    
    0 讨论(0)
提交回复
热议问题