替换字典中的值

时间:2014-11-08 18:18:39

标签: python dictionary replace

当用户从字典值中的字典中选择一个键时,我正在尝试为网站执行上次访问日期和时间。

这是代码:

import webbrowser, time

# -*- coding: utf-8 -*-
web_pages = {1:('Google Scholar','webpage','N/A'),
             2:('Moodle','webpage','N/A'),
             3:('BBC','webpage','N/A'),
             4:('Webmail','webpage','N/A')} 

##------last access date-------------------------
def last_access(x, y):
    ([x] +" "*10+ value[0] +" "*10 +value[1]+" "*10 +[y]+"\n")

##-------output_structure_top---------------------------
def output_structure_top ():
    print "--- MY BOOKMARK MANAGER --- "+"\n"  
    print "Number"+" "*10 +"Name"+" "*30+"Address"+" "*20+"Last accessed"
    print "-"*90+"\n"

##----output_structure_bottom------------------------
def output_structure_bottom():
    print "-"*60+"\n"

while True:
    ui = raw_input("""Enter the number to open a bookmark,
    or enter + to add, - to delete, or x to exit: \n """)
    litems = len(web_pages)
    if ui >= litems:
        ui = int(ui)
        la = (time.strftime("%d/%m/%Y"))+" "+(time.strftime("%H:%M:%S"))

        url = (web_pages[ui][1]) #get the url from the web_pages

        webbrowser.open(url)   #opens the url in a web browser

        output_structure_top()    #print out the top table structure

        last_access(int(ui), la)   #gets the date and time and replaces is it instead of N/A

        output_structure_bottom() #print out the bottom table structure

else:
    print "invalid input!"
    break
`

我得到的是:

   ([x] +" "*10+ value[0] +" "*10 +value[1]+" "*10 +[y]+"\n")
TypeError: can only concatenate list (not "str") to list

我期待的是:

如果用户选择键2,它将在浏览器中打开该URL并打印出来:

   --- MY BOOKMARK MANAGER ---

  Number__________Name_________________Address_________last accessed

  1__________Google Scholar______________webpage_______N/A

  2__________Moodle__________webpage__________08/11/2014 17:40:19

  3__________BBC__________webpage__________N/A

  4__________Webmail__________webpage__________N/A

  ------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

如果xy是字符串,则替换:

([x] +" "*10+ value[0] +" "*10 +value[1]+" "*10 +[y]+"\n")

由:

(x +" "*10+ value[0] +" "*10 +value[1]+" "*10 +y+"\n")