重复一个字符串n次-repeat_string_n_times()
发布时间:2023-09-27 15:50:13
要实现重复一个字符串n次的函数,可以使用循环来实现。以下是一个实现这个功能的函数:
def repeat_string_n_times(s, n):
# 定义一个空字符串
result = ""
# 循环将字符串s重复n次
for i in range(n):
result += s
# 返回结果
return result
这个函数接受两个参数:字符串s和重复次数n。在循环中,我们使用加法操作符将字符串s添加到结果字符串result中,重复n次。最后,将结果字符串返回。
例如,如果调用repeat_string_n_times("hello", 3),函数将返回"hellohellohello"。
