繁体   English   中英

Python:使用replace函数将字符串中的项目替换为列表中的项目

[英]Python: Using replace function to replace item from string with item from list

我正在为一个游戏编写代码,该游戏需要用户输入并用原始字符串(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)

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

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM