String Repetition

We can use * operator to repeat string n number of times. Below is the syntax for repeating string.

str*n

str : Variable containing string and n is the number of times that string will be repeated.

Below are some of the examples.

>> str = ‘Python’
>>> str*4
‘PythonPythonPythonPython’

>> string1 = ‘Python language’
>>> string1*2
‘Python languagePython language’

>> string2 = ‘India is a great country’
>>> string2*3
‘India is a great countryIndia is a great countryIndia is a great country’

We can also use * operator to repeat some part of a string. First slice the string then use * operator to repeat part of a string.

>> string3 = ‘Python is a programming language’
>>> s = string3[3:4]
>>> s*3
‘hhh’

>> s = string3[3:9]
>>> s*3
‘hon ishon ishon is’

>> s = string3[8:13]
>>> s*4
‘s a ps a ps a ps a p’

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s