如何修改Python代码实现字符按位置重复并以-分隔的字符串格式?
问题与解决方案
问题描述
现有如下Python代码:
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的字符串。
修改方案
核心逻辑是让每个字符根据自身在字符串中的位置(从0开始计数),重复「位置索引+1」次,再将所有重复后的片段用-连接。
简洁写法(推荐)
word2 = input("put in the word you want me to repeat: ") print("The original string is: " + word2) # 生成每个重复片段后用-拼接 result = "-".join([char * (i + 1) for i, char in enumerate(word2)]) print(result)
基于原循环的修改写法
如果要保留原代码的循环结构,可以这样调整:
word2 = input("put in the word you want me to repeat: ") letter = "" print("The original string is: " + word2) for x in range(len(word2)): # 第一个片段直接拼接,后续先加分隔符再拼接重复字符 if x == 0: letter += word2[x] * (x + 1) else: letter += "-" + word2[x] * (x + 1) print(letter)
逻辑说明
- 用
enumerate或循环索引x,可以拿到每个字符的位置序号 - 每个字符重复
x+1次:比如第一个字符位置是0,重复1次;第二个位置是1,重复2次,以此匹配需求格式 - 用
"-".join()或循环中判断添加分隔符,实现片段间的-连接
内容的提问来源于stack exchange,提问作者Proxie
相关产品推荐
相关产品推荐

