如何编写一个函数来返回重复n次的字符串,用字符串delim分隔

时间:2017-01-10 02:06:37

标签: computer-science

这假设创建一个函数,该函数可以返回重复n次的字符串,由用户所需的字符串delim分隔。我错过了什么?

def repeat(string, n, delim) :
  return (string + delim) * (n - 1)


def main() :
  string = input("Enter a string: ")
  n = int(input("Enter the number of times repeat: "))
  delim = input("Enter the delim: ")

main()

1 个答案:

答案 0 :(得分:0)

您必须将字符串添加到最后一个:

def repeat(string, n, delim) :
  return (string + delim) * (n - 1) + string


def main() :
  string = input("Enter a string: ")
  n = int(input("Enter the number of times repeat: "))
  delim = input("Enter the delim: ")
  print(repeat(string, n, delim))

main()

输出:

Enter a string: hello
Enter the number of times repeat: 10
Enter the delim: ,
hello,hello,hello,hello,hello,hello,hello,hello,hello,hello