Jowison
Jowison

Reputation: 13

Stuck on an exercise, for/while loops

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.

Upvotes: 0

Views: 42

Answers (1)

cmd
cmd

Reputation: 5830

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))

Upvotes: 3

Related Questions