簡體   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