简体   繁体   中英

How do I put characters inbetween characters

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" ?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM