Monday 22 January 2024

Use * as a string replication operator in Python

When the operator '*'' is applied to two integers or floating-point values, it acts as a multiplication operator. But when it is used with one string and one integer, the * operator transforms into a string replication operator.

* operator between integers, float values

>>> 5 * 4
20
>>> 
>>> 5.5 * 4
22.0
>>>

 

* operator between a string and an integer

>>> 'Ram' * 5
'RamRamRamRamRam'
>>> 
>>> 5 * 'Ram'
'RamRamRamRamRam'

The expression ('Ram' * 5) results in a single string that duplicates the original string as many times as the integer value indicates. While string replication is a handy technique, it is not as commonly used as string concatenation.

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment