Python3如何在4个单词后向数组中的每个元素添加<br/>标签?

时间:2019-04-04 01:21:13

标签: arrays python-3.x

我有一个数组 ElementA

ElementA=["Hello my name is Karen", "Andrew here with you and nice to meet you", "Hi, Sharon here"]

我希望为数组生成一个输出,该输出将返回如下:

OutputElementA= ["Hello my name is <br> Karen", "Andrew here with you <br> and nice to meet <br> you", "Hi, Sharon here"]

每个人都有关于如何在每个元素的4个单词后向数组中的元素添加
标签的想法吗?

1 个答案:

答案 0 :(得分:2)

这应该做到。

ElementA=["Hello my name is Karen", "Andrew here with you and nice to meet you", "Hi, Sharon here"]
OutputElementA = []

for elem in ElementA:
    #Split string into words
    elem_list = elem.split(' ')
    out_elem_str = ''
    i=0
    elem_item = []
    while i < len(elem_list):
        elem_item = elem_list[i:i+4]
        if len(elem_item) == 4:
            out_str = ' '.join(elem_item)+' <br> '
            out_elem_str += out_str
        i+=4
    out_elem_str += ' '.join(elem_item)
    OutputElementA.append(out_elem_str)

print(OutputElementA)

输出为

['Hello my name is <br> Karen', 
'Andrew here with you <br> and nice to meet <br> you', 
'Hi, Sharon here']