Home > Enterprise >  Stuck on an exercise, for/while loops
Stuck on an exercise, for/while loops

Time:09-14

New in python and really stuck on this exercise:

Marvin should ask for a string and print a new string where each character has been incremented by 1 and is separated by "-"

Example: input: "ape" output: "a-pp-eee"

FYI, it's translated from swedish, if there are any weird wordings.

CodePudding user response:

This will iterate over the characters of the word and duplicate each entry by its index 1 (since index is 0 based). Finally joining the results with '-'

print('-'.join(c * (i   1) for i, c in enumerate(word)))

example:

>>> word = 'ape'
>>> print('-'.join(c * (i   1) for i, c in enumerate(word)))
a-pp-eee

without comprehension (to help understand):

string_parts = []
for index, character in enumerate(word):
    string_parts.append(character * (index   1))
print('-'.join(string_parts))
  • Related