2017-04-10 62 views
0

对不起,如果标题不够描述。基本上,我有一个像将单词插入列表中的特定位置

["The house is red.", "Yes it is red.", "Very very red."] 

名单,我想第一个字符前插入字"super",中间字符之间和每个字符串的最后一个字符之后。所以我会有这样的第一个元素:

["superThe houssupere is red.super",...] 

我该怎么做?我知道用字符串我可以使用添加"super"字符串到我的字符串的开头,然后使用len()去字符串的中间,并添加"super"。有没有办法让这个与列表一起工作,还是我应该尝试一种不同的方法?

+1

欢迎来到SO。请告诉我们您到目前为止所尝试的内容,以及什么不起作用(完整的错误信息,或者您获得的结果与您预期的结果相比较)。那么我们可以帮助你解决你的问题! –

+1

'['super {0} super {1} super'.format(i [:len(i)// 2],i [len(i)// 2:])for i in li]'?.这看起来像是......奇怪的请求。 – miradulo

+0

您已经知道如何使用单个字符串来完成此操作。假设你有一个函数make_super_string(x)。试试map(make_super_string,the_list)。通常,您可以遍历列表来更改每个条目,也可以创建一个新列表(也可以将其分配给同一个变量)。 –

回答

0

此处使用的方法是遍历原始列表,将每个项目拆分成两半,然后使用.format构建最终项目字符串,然后将其附加到新列表中。

orig_list = ["The house is red.", "Yes it is red.", "Very very red."] 
new_list = [] 
word = 'super' 

for item in orig_list: 
    first_half = item[:len(item) // 2] 
    second_half = item[len(item) // 2:] 
    item = '{}{}{}{}{}'.format(word, first_half, word, second_half, word) 
    new_list.append(item)