简体   繁体   English

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

[英]How do I move a part of a string, for every item in a list

I have made a program in Python which should, for every item in the list, move a certain substring "{Organization}" to the end of the item.我在 Python 中编写了一个程序,对于列表中的每个项目,它应该将某个 substring "{Organization}"移动到项目的末尾。

The list: example_list = ['Wall{Organizationmart', 'is', 'a', 'big', 'company']列表: example_list = ['Wall{Organizationmart', 'is', 'a', 'big', 'company']

This is the code I made这是我制作的代码

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

The expected output is: ['Wallmart{Organization}', 'is', 'a', 'big', 'company']预期的 output 是: ['Wallmart{Organization}', 'is', 'a', 'big', 'company']

However, this is the output:但是,这是 output:

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

Any help would be appreciated.任何帮助,将不胜感激。 Thank you very much.非常感谢。

You forgot to check if organization is in each string.您忘记检查组织是否在每个字符串中。 Slight modification to your code:对您的代码稍作修改:

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: Output:

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


Same thing with list comprehension:与列表理解相同:

output = [i.replace(word, "") + str(word) + "}" if word in i else i for i in example_list]

You must check if the word is in the list element and decide what to print according to that.您必须检查单词是否在列表元素中,并据此决定要打印的内容。 The solution to your problem is:您的问题的解决方案是:

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)

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

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