繁体   English   中英

如何在字符之间放置字符

[英]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]

所以如果我输入"dwas"它只会打印"dwas" 如何让它打印"d-ww-aaa-ssss"

您可以使用enumerate从输入中传递字符串值,并将起始值作为1 ,然后重复字符n次,最后通过-加入:

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

通过组合内置函数:

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

类似于问题中的 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.

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