简体   繁体   中英

Convert list of integers to strings

I need to remove files from all the /etc/rc*.d/ directories. I can't figure out how to convert integers to strings in an list.

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"

This give me: TypeError: cannot concatenate 'str' and 'list' objects. Appreciate any guidance.

The elements of RC are already strings, so:

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"

Your list is in string format. Maybe you meant [3,4,5]. You cannot use str or int or float functions on a list. You need to use the map function to convert a list to string. In your example, the problem is str(RC). If your list is integer try this:

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"

or you can use str() for each element of your list.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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