You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于另一字符串长度逐字符重复单词(Python实现)

Python实现按目标文本长度逐字符重复指定单词(含空格格式适配)

基础版本:匹配目标文本长度重复单词字符

你原来的代码逻辑存在问题,会持续重复单词的单个字符而非循环整个单词。以下是修正后的实现,可生成与目标文本长度一致、循环重复指定单词的结果:

ex_text = 'I am an example test text'  # 长度25
ex_word = 'coding'

# 计算完整重复次数与剩余字符数
total_len = len(ex_text)
word_len = len(ex_word)
full_repeats = total_len // word_len
remaining_chars = total_len % word_len

# 拼接最终结果
rep_word = ex_word * full_repeats + ex_word[:remaining_chars]
print(rep_word)

输出结果:

codingcodingcodingcodingc

也可以用itertools.cycle实现更简洁的循环取字符逻辑:

from itertools import cycle

ex_text = 'I am an example test text'
ex_word = 'coding'

rep_word = ''.join([next(cycle(ex_word)) for _ in range(len(ex_text))])
print(rep_word)

该版本会逐个循环提取ex_word的字符,直到凑够目标文本长度,结果与上述代码一致。


进阶版本:适配原文本的空格格式

如果需要保留原文本的空格位置,仅在非空格处填充单词字符,可按以下逻辑实现:

ex_text = 'I am an example test text'
ex_word = 'coding'

word_iter = cycle(ex_word)
rep_word = []

for char in ex_text:
    if char == ' ':
        rep_word.append(' ')
    else:
        rep_word.append(next(word_iter))

rep_word = ''.join(rep_word)
print(rep_word)

输出结果类似:

c od in gcoding codi ngco

该逻辑遍历原文本的每个字符,遇到空格直接保留,非空格位置则从循环的单词序列中取下一个字符,完美匹配原文本的空格布局。

内容的提问来源于stack exchange,提问作者MeTomaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:20:28