如何为列表中的每个项目移动字符串的一部分
How do I move a part of a string, for every item in a list
我在 Python 中编写了一个程序,它应该针对列表中的每个项目,将某个子字符串 "{Organization}"
移动到项目的末尾。
榜单:example_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 = '{Organization'
for i in example_list:
if word in i:
output.append(i.replace(word, "") + str(word) + "}")
else:
output.append(i)
print(output)
输出:
['Wallmart{Organization}', 'is', 'a', 'big', 'company']
与列表理解相同:
output = [i.replace(word, "") + str(word) + "}" if word in i else i for i in example_list]
我在 Python 中编写了一个程序,它应该针对列表中的每个项目,将某个子字符串 "{Organization}"
移动到项目的末尾。
榜单:example_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 = '{Organization'
for i in example_list:
if word in i:
output.append(i.replace(word, "") + str(word) + "}")
else:
output.append(i)
print(output)
输出:
['Wallmart{Organization}', 'is', 'a', 'big', 'company']
与列表理解相同:
output = [i.replace(word, "") + str(word) + "}" if word in i else i for i in example_list]