TAN-C-F-OK
TAN-C-F-OK

Reputation: 179

Add characters to specific elements in a list

I have a list like:

['We', 'HELLO', 'want', 'you', 'WOHO', 'self', 'Maybe', 'APIL', 'sort', ...]

Now i want to add first word 'We' something like '<a>We</a>' and the same for 'you' and every third word from now on. So the first word in the list and form then on every third word i want to add <a></a>. The same i want for the second word, like <b></b>, and again every third word. And, of course, for the third word and then again for every third word after.

I am totally off right now.

I tried to split that big list in a lot of lists with only 3 words each. So i can address the words in the list with [0], [1], [2]. But its unbelievable complicated. Is there a better solution?

I want something like:

<a>We</a>
<b>HELLO</b>
<c>want</c>
<a>you</a>
<b>WOHO</b>
<c>self</c>
<a>Maybe</a>
<b>APIL</b>
<c>sort</c>
...

Upvotes: 0

Views: 30

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113915

import itertools

chars = 'abc'
tags = itertools.cycle(chars)
words = ['We', 'HELLO', 'want', 'you', 'WOHO', 'self', 'Maybe', 'APIL', 'sort']

for word, tag in zip(words, tags):
    print("<{0}>{1}</{0}>".format(tag, word))

Output:

<a>We</a>
<b>HELLO</b>
<c>want</c>
<a>you</a>
<b>WOHO</b>
<c>self</c>
<a>Maybe</a>
<b>APIL</b>
<c>sort</c>

Upvotes: 3

Related Questions