【问题标题】:Replacing words in a string- but with two different words: Python3用两个不同的词替换字符串中的单词:Python3
【发布时间】:2013-10-31 23:13:47
【问题描述】:

试图得到它,以便它接受输入的特定单词出现在原始字符串中的相同次数,并将其替换为输入的每个单词。

def replace_parts_of_speech (replaced, part_of_speech):
    '''Finds and replaces parts of speech with words '''
    new_line=''

    for i in range (replaced.count(part_of_speech)):
        new=input('Enter '+ part_of_speech +':') 
        new_line = replaced.replace(part_of_speech,new,1)


    return new_line

【问题讨论】:

  • 这是给 Mad Libs 的,是吗?您能否发布示例输入以及您期望的输出是什么?
  • replace_parts_of_speech ('noun in noun verb', 'noun') Enter noun= 1 Enter noun= 2 预期:'1 in 2 verb' 得到:'2 in noun verb'
  • 将预期输出添加到您的问题而不是 cmets

标签: python string loops python-3.x


【解决方案1】:

问题在于,每次循环时,您都会创建一个全新的new_line,而忽略之前的new_line,而只是回到原来的replaced。因此,循环完成后,只有最后一个替换可见。

for i in range (replaced.count(part_of_speech)):
    new=input('Enter '+ part_of_speech +':') 
    new_line = replaced.replace(part_of_speech,new,1)

所以,第二个替换忽略了第一个。

你想做的是这样的:

new_line = replaced
for i in range (replaced.count(part_of_speech)):
    new=input('Enter '+ part_of_speech +':') 
    new_line = new_line.replace(part_of_speech,new,1)

同一问题的简化示例可能更容易理解:

start = 0
current = 0
for i in range(5):
    current = start + i
print(current)

这只会打印4。但是现在:

start = 0
current = start
for i in range(5):
    current = current + i
print(current)

这将打印10

【讨论】:

  • 完全正确-感谢您澄清这一点。我的大脑简直昏昏欲睡。 :)
猜你喜欢
  • 2014-01-08
  • 2023-02-07
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
  • 2022-07-05
  • 1970-01-01
  • 2016-04-20
相关资源
最近更新 更多