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
相关产品推荐
相关产品推荐

