[英]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.