Python 如何为列表中的每个项目移动字符串的一部分

Python 如何为列表中的每个项目移动字符串的一部分,python,list,substring,Python,List,Substring,我用Python编写了一个程序,对于列表中的每个项目,都应该将某个子字符串“{Organization}”移动到项目的末尾 列表:example\u list=['Wall{Organizationmart','is','a','big','company'] 这是我写的代码 output = [] word = '{Organization' for i in example_list: output.append(i.replace(word, "") + str

我用Python编写了一个程序,对于列表中的每个项目,都应该将某个子字符串
“{Organization}”
移动到项目的末尾

列表:
example\u list=['Wall{Organizationmart','is','a','big','company']

这是我写的代码

output = []
word = '{Organization'
for i in example_list:
    output.append(i.replace(word, "") + str(word) + "}")
print(output)
预期的输出是:
['Wallmart{Organization}'、'is'、'a'、'big'、'company']

但是,这是输出:

['Wallmart{Organization}', 'is{Organization}', 'a{Organization}', 'big{Organization}', 'company{Organization}']

任何帮助都将不胜感激。非常感谢。

您必须检查单词是否在列表元素中,并根据列表元素决定打印什么。 您的问题的解决方案是:

example_list = ['Wall{Organizationmart', 'is', 'a', 'big', 'company']

output = []
word = '{Organization'
for i in example_list:
    if word in i:
        output.append(i.replace(word, "") + str(word) + "}")
    else:
        output.append(i)
print(output)

如果每个字符串中都有组织,则忘记检查组织。对代码的轻微修改:

output=[]
word=“{组织”
对于示例_列表中的i:
如果i中的单词:
output.append(i.replace(单词“”)+str(单词)+“}”)
其他:
输出追加(i)
打印(输出)
输出:

['Wallmart{Organization}'、'is'、'a'、'大'、'公司']


列表理解也是如此:

output=[i.replace(word,“”)+str(word)+“}”if-in-i-else-i-for-i-in-example_-list]

所以您只想在第一项中添加您的文字?谢谢您的评论。我只想删除单词+只在这个单词中有{Organization}时才在单词后面添加单词。我想我找到了。我在示例中添加了一个'if'语句:在I:output.append(I.replace(word,“”)+str(word)+“}”)中添加了I,它只将我作为输出['Wallmart{Organization}]现在,我还向输出中添加了不包含“{Organization”的单词:例如I中的I_list:if-word-in-I:output.append(I.replace(word,“”)+str(word)+“}”)if-in-I:output.append(I)您是正确的,一个简单的if语句可以解决您的问题!您只需在每个字符串之前添加一个f,即可将其标记为格式字符串。谢谢