【问题标题】:How to repeat a string until the length of another string, including spaces?如何重复一个字符串直到另一个字符串的长度,包括空格?
【发布时间】:2025-11-25 16:30:01
【问题描述】:

例如,

string1 = "The earth is dying"`
string2:"trees" 

我想要一个新字符串:tre estre es trees

我正在考虑将第一个字符串拆分为一个列表并进行迭代,但我无法获得第二个 for 循环,该循环将迭代第二个字符串并将其添加到第一个字符串,直到达到正确的长度?另外,我会有某种类型的 if 语句来检查空格并将它们添加到最终列表中。然后可能加入最终名单?

final_string = ''
string1_list = list(string1)
for i in range(string1_list):
    if string1_list[i] != " " #aka has a letter there
        for j in range(...) # how do I get a loop that would go through string2
        final_string += ... # and add into this string 

【问题讨论】:

  • 随时发布您的代码尝试,我们一定能够帮助您解决问题。 :) - 你的想法是一个好的开始!

标签: python string list for-loop


【解决方案1】:
string1 = "The earth is dying"
string2 = "trees" 
result = ""
index = 0
for character in string1:
    if character == " ":
        result += " "
    else:
        result += string2[index%len(string2)]
        index+=1
print(result)

输出:"tre estre es trees"

【讨论】:

  • 如果我要遍历结果,它会将结果 [i] 打印为字母块,但我该如何做到这一点,以便如果我打印结果 [i] 它会像 t,r, e, ,s, ... 与现在的 tres,estre 相比如何?
【解决方案2】:

itertools.cycle魔法

from itertools import cycle

s1 = "The earth is dying"
s2 = "trees"

gen = cycle(s2)
res = ''.join(c if c.isspace() else next(gen) for c in s1)
print(res)

输出:

tre estre es trees

【讨论】:

    最近更新 更多