Home > Software design >  How do I put characters inbetween characters
How do I put characters inbetween characters

Time:09-09

word2 = input("put in the word you want me to repeat: ")
letter = ""
print("The original string is: "   word2)

for x in range(len(word2)):
    letter  = word2[x]

So if i put in "dwas" it will just print "dwas". How do I make it print "d-ww-aaa-ssss"?

CodePudding user response:

You can use enumerate passing the string value from input, and the start value as 1, then repeat the characters n times, and finally join by -:

>>> print('-'.join(v*i for v,i in enumerate(inp,1)))
d-ww-aaa-ssss

CodePudding user response:

By composiing built-in functions:

s = "hallo"
new_s = '-'.join(map(str.__mul__, s, range(1, len(s) 1)))
print(new_s)
#h-aa-lll-llll-ooooo

A for loop approach similar to the one in the question

s = "hallo"

# construct the output character per character
new_s = ''
# iterate over (index, character)-pairs, index start from 1 
for i, char in enumerate(s, 1):
    # add to output i-times the same character followed by -
    new_s  = f'{char*i}-'

# remove the last character (always the -)
new_s = new_s.rstrip('-')

# check result
print(new_s)
  • Related