Repeat String with Python Operator

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can use the * operator to repeat a string a certain number of times. This can be useful in many situations, such as when we need to create a string with a specific number of characters or when we need to repeat a certain pattern.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13698{{"`Repeat String with Python Operator`"}} python/tuples -.-> lab-13698{{"`Repeat String with Python Operator`"}} python/function_definition -.-> lab-13698{{"`Repeat String with Python Operator`"}} end

Repeat String

Write a function called repeat_string that takes two parameters: a string s and an integer n. The function should return a new string that contains s repeated n times.

For example, if s is "hello" and n is 3, the function should return "hellohellohello". If s is "abc" and n is 5, the function should return "abcabcabcabcabc".

def n_times_string(s, n):
  return (s * n)
n_times_string('py', 4) #'pypypypy'

Summary

In this challenge, you learned how to use the * operator to repeat a string a certain number of times. You also wrote a function called repeat_string that takes a string and an integer as parameters and returns a new string that contains the original string repeated n times.

Other Python Tutorials you may like