如何在特定位置将字符串添加到另一个字符串?

时间:2019-07-08 20:14:50

标签: python for-loop if-statement

我在解决这一挑战时遇到了一些困难:

对于单词中的每个单词,如果单词以“ e”结尾以使其超过时态,则在单词的末尾添加“ d”。否则,请添加“ ed”以使其超过时态。将这些过去时词保存到一个名为past_tense的列表中。

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]

我的尝试是:

enter code here:


words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []
for i in words:
   if i[-1] == "e":
       past_tense.append(i+"d")
   else:
       past_tense.append(i+"ed")
print(past_tense)

2 个答案:

答案 0 :(得分:0)

我会在列表理解中使用内联if-else构造:

past_tense = [w + 'd' if w.endswith('e') else w + 'ed' for w in words]

答案 1 :(得分:0)

我敢肯定,这样做有更多的Python方式,但这是可以理解的!

使用评论中提到的str.endswith可以节省大量时间!

words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
new_list=[]
for i in words:
    if i.endswith('e'):
        new_list.append(i+'d')
    else:
        new_list.append(i+'ed')
print(new_list)

这将输出您过去的清单!

['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']