2016-09-24 142 views
0

我想写一个函数解码(chmod),它将一个三位数的权限编号作为一个字符串并返回它授予的权限。 它似乎工作,除非我要求第零个元素。我无法弄清楚为什么如此。Python列表第零个元素混合

def decode(chmod): 

    liste = [int(i)for i in str(chmod)] 


    chmod = ["None", "Execute only", "Write only", 
     "Write and Execute", "Read only", 
     "Read and Execute", "Read and Write", 
     "Read Write and Execute"] 

    for i in liste: 

     print chmod[i] 

    return liste 

print decode(043) 

回答

1

您需要在043前后引号。尝试'043'。

+0

感谢您的答复。但我不应该参与投入。我只是测试它是否有效。 – janvar

+1

当python看到043时,它认为它是一个八进制格式的整数。你的解码函数会得到这个intger。对str()做的不是你想要的。如果你想传递八进制整数,你应该将它转换回八进制字符串表示。 (str()不够)。 – sureshvv

+1

@grv:你写的描述是这样的:“将三位数的权限号**作为字符串**”。但在你的测试中,你没有传递一个字符串;你传递一个整数。因此需要报价。 –

1

(假设要传递的整数)

043是基座8是相同35在基座10您因此传递给解码功能的整数35。

尝试改变str - >oct

liste = [int(i) for i in oct(chmod)[2:]] #Use [2:] in Py3, and [1:] in Py2 
+0

或者只是'liste = oct(chmod)',因为'for i in liste'会迭代每个符号。 – AArias

+0

您可能希望'oct(chmod)[2:]'切断'0o'前缀。或者'format(chmod,'03o')'来确保你总是得到一个三位八进制字符串。 –

+0

@MarkDickinson:谢谢,我错过了它是Py2中的'043'和Py3中的'0o43'。更新了我的答案。 :) – SuperSaiyan

相关问题