Python:使用replace函数将string中的item替换为list中的item

时间:2014-10-05 23:17:31

标签: python

我正在为一个游戏编写代码,该游戏从用户那里获取输入并用原始字符串中的一段代码替换该字符串输入(old_story)我不断返回此TypeError。我想这样做,以便我的代码用new_word_list中相应的迭代号替换replace_this字符串(值在代码中早先分配给该列表)。有什么方法可以解决这个问题吗?有多个replace_this字符串,以及new_word_list中相同数量的项目。我怎样才能让它顺利运行?任何建议都将受到高度赞赏,因为文档令人困惑。我知道这是一个非常简单的问题,但我很感激我能得到的任何帮助。这是继续在IDLE中返回的错误:TypeError:无法转换' list'隐含地反对str


import random
old_story = random.choice(open('madlibs.txt').readlines())

new_word_list = [""] #new list where user input will be added to.
end = 0
repetitions = old_story.count('{')
for i in range(repetitions):
    start = old_story.find('{', end) + 1
    end = old_story.find('}', start)
    replace_this = old_story[start:end]
    replace_this = input("Please enter a " + replace_this + ":")
    new_word_list.append(str(replace))

new_story = old_story
for i, replace_this in enumerate(old_story):
    if i > len(new_word_list) - 1:
        break
    new_story = old_story.replace(replace_this, new_word_list[i])

new_story = new_story.strip()
print(new_story)

1 个答案:

答案 0 :(得分:-1)

您无法传递列表本身,您需要通过索引访问列表中的项目:

s = "foo foobar foo"
l = ["hello world "]

print s.replace("foobar",l[0])
foo hello world  foo

l = ["hello world ","different string"]

print s.replace("foobar",l[-1])
foo different string foo



old_story =  "This is a {word}."
new_word_list = ["one","two","three","four"]

spl = old_story.split() #  split  into individual words
for ind, new_s in enumerate(new_word_list):
    spl[ind] = new_s # replace element at matching index
print (" ".join(spl)) # rejoin string from updated list
one two three four

old_story =  "This {foo} is {a} {foo} {bar}."
new_word_list = ["is","my","final","solution"]
spl = old_story.split()
for ind, word in enumerate(spl):
    if word.startswith("{"):
         spl[ind] = new_word_list.pop(0)
print (" ".join(spl))
This is is my final solution

如果您有变量,可以将它们与str.format

一起使用
old_story = " Hello! I {verb} a {noun} today!"

new_word_list = ["is","my","final","solution"]
verb, noun = ["ate","hotdog"]

print( old_story.format(verb=verb,noun=noun))
 Hello! I ate a hotdog today!