Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to convert octal to string eg octal(755) to (rwxr-xr-x). Stuck at adding the dash seperator

Tags:

python

Below is the script printing the converted octal to string. I would appreciate suggestion on how to add the - separator to the string on each permission (r/w/x)

def octal_to_string(octal):
    result = ""
    value_letters = [(4,"r"),(2,"w"),(1,"x")]
    #Iterating over each digit in octal
    for digit in [int(n) for n in str(octal)]:

        #Checking for each of permission values
        for value, letter in value_letters:
            if digit >= value:
                result += letter
                digit -= value
            else:
                pass
    return result

I currently get:

In [7]: octal_to_string(755)
Out[7]: 'rwxrxrx'

In [8]: octal_to_string(644)
Out[8]: 'rwrr'
like image 809
Karimi254 Avatar asked Feb 25 '20 12:02

Karimi254


1 Answers

Change the pass to result += "-":

def octal_to_string(octal): 
    result = "" 
    value_letters = [(4,"r"),(2,"w"),(1,"x")] 
    #Iterating over each digit in octal 
    for digit in [int(n) for n in str(octal)]: 

        #Checking for each of permission values 
        for value, letter in value_letters: 
            if digit >= value: 
                result += letter 
                digit -= value 
            else: 
                result += "-" 
    return result 

print(octal_to_string(755))

Output:

rwxr-xr-x
like image 95
Joan Lara Ganau Avatar answered Oct 06 '22 03:10

Joan Lara Ganau