如何替换函数中的用户输入

时间:2012-01-13 15:11:46

标签: python

我正在尝试将用户选择写入文本文件。这很完美。用户选择如下:

1

2

3

...

def write_log(name, total):
   # This writes a passed info into text
   logfile = open("text.txt", "a")

   towrite = name
   towrite += " "
   towrite += total
   towrite += "\n"

   try:
       logfile.write(towrite)
   finally:
       logfile.close()

   return write_log


我正在尝试用其他名称替换用户选择。 像这样的东西:


change = [(1, triangle), (2, square), (3, rectangle), (4, pentagon)]


当我这样做时它不起作用


def write_log(name, total):
   # This writes a passed info into text
   change = [(1, triangle), (2, square), (3, rectangle), (4, pentagon)]
   for search, replace in change:
      name = name.replace(search, replace)
   logfile = open("text.txt", "a")

   towrite = name
   towrite += " "
   towrite += total
   towrite += "\n"

   try:
       logfile.write(towrite)
   finally:
       logfile.close()

   return write_log

2 个答案:

答案 0 :(得分:0)

我会用字典:

def write_log(name, total):
   change = {1: 'triangle', 2: 'square', 3: 'rectangle', 4: 'pentagon'}

   name = change.get(name, 'other')
   towrite = "%s %d\n" % (name, total)
   logfile = open("text.txt", "a")

   try:
       logfile.write(towrite)
   finally:
       logfile.close()

答案 1 :(得分:0)

这就是我要用的:

def write_log(name, total):
    #{n} is better than to replace a number if it's user input,
    #where n is the index of each item in change. I.E {0} == change[0] == "triangle"
    change = ["triangle", "square", "recrangle", "pentagon"]#remember that {n} refers to a position in this list.
    towrite = "%s %s\n" % (name.format(*change), total)
    with open("text.txt", "a") as logfile:#With closes a file automatically for you, in fewer lines.
        logfile.write(towrite)

如果您想要字符串替换,请执行以下操作:

towrite = "%s %s\n" % (name.format(*change), total.format(*change))

如果“* change”不起作用,你可以自己解压缩列表(name.format(“triangle”,“rectangle”......))

祝你好运:)