我正在尝试使用replace函数从列表中获取项目并将下面的字段替换为其相应的值,但是无论我做什么,它似乎只有在达到范围的末尾时才起作用(在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()
###Program Starts#####--------------------
while True==True:
objective = input("What would you like to do?\n1. Create a new document\n2. Fill in a document with fieldnames\n")
if objective == 1:
writeDocument()
elif objective == 2:
fillDocument()
else:
print "That's not a valid choice."
消息文件:
<<name>> <<color>> <<age>>
字段名称文件:
<<name>>
ryan
<<color>>
blue
<<age>>
18
答案 0 :(得分:1)
原因:
这是因为除从“字段名”文件中读取的最后一行以外的所有行均包含“ \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>>
字段被替换。(您必须有一个“ { {1}}”添加到msg文件的末尾,否则也将无法替换。)
解决方案:
在读取行时使用\n
方法在结尾处去除换行符。
rstrip()