Table of Contents
In Python, the print()
function is used to display some results on the output console. The print()
function has evolved in Python. It started as a statement and it wasn’t until Python 3 that it was changed to a function.
Print Character n Times in Python
We will discuss how to print a character n times in Python.
Using the *
operator
The *
operator can be used in different ways with different objects in Python. We can use it to perform arithmetic multiplication, unpack elements, and now we will discuss how to use it to print a character n times in Python.
In the print()
function we can specify the character to be printed. We can use the *
operator to mention how many times we need to print this value.
See the code below.
1 2 3 |
print('a'*5) |
Output:
In the above example, we printed the character five times using the *
operator.
In case, if you are using Python 2.x, here is the syntax.
1 2 3 |
print 'a' * 5 |
In case, you want to use separator such as _
, here is syntax to use separator.
1 2 3 |
print(*5*('a',), sep='_') |
Output:
As you can see, repeating character is separated by -
.
Further reading:
Using the for
loop
The range()
function is used in Python to create a sequence between the provided range. We can iterate over this sequence with the for
loop.
We can use the for
loop to print a character n times in Python. For this, we will iterate over the sequence of required length and print the character in every iteration.
1 2 3 4 |
for i in range(5): print('a') |
Output:
a
a
a
a
In the above example, we create a sequence using the range()
function and print the character in every iteration of the sequence using the for
loop. Note that the character is displayed in a new line in every iteration.
Print String n times in Python
To print String n times in Python, you can use *
with String as well.
1 2 3 4 |
str1="Hello" print(str1*3) |
Print Number n times in Python
To print number n times, you can convert it to String using single quotes or str() function and print it using *
.
To print number 2
5 times, you can use following code:
1 2 3 |
print('2'*5) |
Output:
You can also use str()
function to convert int to String.
1 2 3 |
print(str(2) * 5) |
Output:
Conclusion
In this tutorial, we discussed how to print a character n times in Python. There are two methods for this. In the first method, we used the *
operator in the print()
function to print it the required times. We also discussed the use of the for
loop to print a character n times in Python.