[英]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"
.所以如果我输入"dwas"
它只会打印"dwas"
。 How do I make it print "d-ww-aaa-ssss"
?如何让它打印"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 -
:您可以使用enumerate
从输入中传递字符串值,并将起始值作为1
,然后重复字符n
次,最后通过-
加入:
>>> 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类似于问题中的 for循环方法
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.