繁体   English   中英

将整数列表转换为字符串

[英]Convert list of integers to strings

我需要从所有 /etc/rc*.d/ 目录中删除文件。 我不知道如何将整数转换为列表中的字符串。

RC = ["3","4","5"]
for RCS in str(RC):
    if (os.path.exists("/etc/rc"+RC+".d/file")):
       os.remove("/etc/rc"+RC+".d/file")
    else:
       print "/etc/rc"+str(RC)+".d/file is not a file"

这给了我: TypeError: cannot concatenate 'str' and 'list' objects。 感谢任何指导。

RC 的元素已经是字符串,所以:

RC = ["3","4","5"]
for RCS in RC:
    if (os.path.exists("/etc/rc" + RCS + ".d/file")):
        os.remove("/etc/rc" + RCS + ".d/file")
    else:
        print "/etc/rc"+ RCS +".d/file is not a file"

您的列表是字符串格式。 也许你的意思是 [3,4,5]。 您不能在列表中使用 str 或 int 或 float 函数。 您需要使用 map function 将列表转换为字符串。 在您的示例中,问题是 str(RC)。 如果您的列表是 integer 试试这个:

RC = [3,4,5]
for RCS in map(str, RC):
    if (os.path.exists("/etc/rc"+RCS +".d/file")):
        os.remove("/etc/rc"+RCS +".d/file")
    else:
        print "/etc/rc"+RCS +".d/file is not a file"

或者您可以将 str() 用于列表的每个元素。

for RCS in RC:
if (os.path.exists("/etc/rc"+str(RCS) +".d/file")):
    os.remove("/etc/rc"+str(RCS) +".d/file")
else:
    print "/etc/rc"+str(RCS) +".d/file is not a file"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM