替换功能不适用于列表项

我正在尝试使用替换功能从列表中获取项目并将下面的字段替换为其相应的值,但无论我做什么,它似乎只在到达范围的末尾时才起作用(在它的最后一个可能值上)的 i,它成功地替换了一个子字符串,但在此之前它没有)


    for i in range(len(fieldNameList)):

        foo = fieldNameList[i]

        bar = fieldValueList[i]

        msg = msg.replace(foo, bar)

        print msg

这是我运行该代码后得到的


<<name>> <<color>> <<age>>


<<name>> <<color>> <<age>>


<<name>> <<color>> 18

我已经被困在这个问题上太久了。任何建议将不胜感激。谢谢 :)


完整代码:


def writeDocument():

    msgFile = raw_input("Name of file you would like to create or write to?: ")

    msgFile = open(msgFile, 'w+')

    msg = raw_input("\nType your message here. Indicate replaceable fields by surrounding them with \'<<>>\' Do not use spaces inside your fieldnames.\n\nYou can also create your fieldname list here. Write your first fieldname surrounded by <<>> followed by the value you'd like to assign, then repeat, separating everything by one space. Example: \"<<name>> ryan <<color>> blue\"\n\n")

    msg = msg.replace(' ', '\n')

    msgFile.write(msg)

    msgFile.close()

    print "\nDocument written successfully.\n"


def fillDocument():

    msgFile = raw_input("Name of file containing the message you'd like to fill?: ")

    fieldFile = raw_input("Name of file containing the fieldname list?: ")


    msgFile = open(msgFile, 'r+')

    fieldFile = open(fieldFile, 'r')


    fieldNameList = []

    fieldValueList = []

    fieldLine = fieldFile.readline()

    while fieldLine != '':

        fieldNameList.append(fieldLine)

        fieldLine = fieldFile.readline()

        fieldValueList.append(fieldLine)

        fieldLine = fieldFile.readline()


    print fieldNameList[0]

    print fieldValueList[0]

    print fieldNameList[1]

    print fieldValueList[1]

    msg = msgFile.readline()


    for i in range(len(fieldNameList)):

        foo = fieldNameList[i]

        bar = fieldValueList[i]

        msg = msg.replace(foo, bar)

        print msg


    msgFile.close()

    fieldFile.close()


浮云间
浏览 160回答 1
1回答

交互式爱情

原因:这是因为除了从“Fieldname”文件读取的最后一行之外的所有行都包含“ \n”字符。所以,当该程序涉及到更换部件fieldNameList,fieldValueList以及msg看起来像这样:fieldNameList = ['<<name>>\n', '<<color>>\n', '<<age>>\n']fieldValueList = ['ryan\n', 'blue\n', '18']msg = '<<name>> <<color>> <<age>>\n'所以 replace() 函数实际上在 msg 字符串中搜索'<<name>>\n', '<<color>>\n','<<age>>\n'并且只有<<age>>字段被替换。(你必须\n在 msg 文件的末尾有一个“ ”,否则它也不会被替换)。解决方案:rstrip()读取行时使用方法删除末尾的换行符。fieldLine = fieldFile.readline().rstrip()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python