Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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:

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?

like image 911
brandonsimpkins Avatar asked Sep 14 '13 21:09

brandonsimpkins


People also ask

How do you find the octal value of a string in Python?

Python oct() function is used to get an octal value of an integer number. This method takes an argument and returns an integer converted into an octal string. It throws an error TypeError if argument type is other than an integer.

What is the use of OCT () function in Python?

The oct() function converts an integer into an octal string. Octal strings in Python are prefixed with 0o .

Which Python method is used to convert values to strings?

We can convert numbers to strings through using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

What will be the correct syntax for the conversion of decimal to octal Python?

# Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.")


1 Answers

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
like image 178
Jon Clements Avatar answered Oct 14 '22 03:10

Jon Clements