For loops - Iterating Strings#

Download exercises zip#

Let’s see some exercise about strings.

Exercise - Impertinence#

Given the sequence of characters having a length multiple of 3, write some code which puts into variable triplets all the sub-sequences of three characters

Example - given:

sequence = "IMPERTINENCE"
            IMPERTINENTE

after your code, it must result:

>>> print(triplets)
['IMP', 'ERT', 'INE', 'NCE']
[ ]:
sequence = "IMPERTINENCE"  # ['IMP', 'ERT', 'INE', 'NCE']
#sequence = "CUTOUT"       # ['CUT', 'OUT']
#sequence = "O_o"          # ['O_o']

# write here

Show solution

[ ]:
sequence = "IMPERTINENCE"  # ['IMP', 'ERT', 'INE', 'NCE']
#sequence = "CUTOUT"       # ['CUT', 'OUT']
#sequence = "O_o"          # ['O_o']

triplets = []
for i in range(len(sequence)):
    if i % 3 == 0:
        triplets.append(sequence[i:i+3])
print(triplets)

Exercise - rosco#

✪✪ Given a string word and string repetitions containing only digits, write some code which puts in variable result a string containing all the characters of word repeated by the number of times reported in the corresponding position of repetitions.

Example - given:

word, repetitions = "rosco", "14323"

After your code it must result:

>>> result
'roooosssccooo'
[ ]:
word, repetitions = "rosco", "14323"      # 'roooosssccooo'
word, repetitions = "chocolate", "144232312"  # 'chhhhooooccooollaaatee'

# write here

Show solution

[ ]:
word, repetitions = "rosco", "14323"      # 'roooosssccooo'
word, repetitions = "chocolate", "144232312"  # 'chhhhooooccooollaaatee'

res = []

for i in range(len(word)):
    res.append(word[i]*int(repetitions[i]))

result = "".join(res)
print(result)

Continue#

Go on with For loops - Iterating Lists