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

Python中如何重复字符串多次且各重复项之间添加空格?

问题分析

你当前的实现return word * n只会对字符串做无分隔拼接,传入hello和3时会得到hellohellohello,无法满足空格分隔的要求。

实现方案

推荐使用Python内置的str.join()方法实现,逻辑简洁且不需要额外处理多余空格:

def repeating(word, n):
    return ' '.join([word] * n)

方案说明

  • 首先通过[word] * n生成包含n个目标字符串的列表,示例场景下会生成["hello", "hello", "hello"]
  • 再用' '.join()方法以空格作为分隔符,把列表所有元素拼接为一个完整字符串
  • 调用示例:repeating("hello", 3)输出结果为hello hello hello,完全符合预期。

如果不想用列表生成的方式,也可以用如下写法,先拼接空格再去掉末尾多余的空格:

def repeating(word, n):
    return ((word + ' ') * n).rstrip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:18:03