Python Percentage Sign
In Python, the percentage sign significantly completes two things. They are:
- It goes about as a Modulo administrator.
- It helps in string organizing.
Allow us to see every one of them plainly.
Modulo operator:
Like the addition (+), subtraction(- ), multiplication (*) and division (/), the modulo (%) is additionally a math administrator which assesses the rest of the division between two operands. These operands can be any number or float.
Language syntax: a % b
Allow us to assume if the modulo administrator is applied between two numbers an and b i.ea%b, it computes the rest of partitioning the main number a with the second number b.
Program:
a = 11
b = 2
c = a % b
print(c)
Output:
1
String organizing utilizing % percentage sign:
Like the other programming dialects like C, the % rate sign can be utilized to organize the string. Consequently, it is otherwise called the string designing administrator. A portion of the placeholders in Python are:
- %d - for whole number
- %f - for float
- %s - for string
- %o - for octal number
- %x - for hexadecimal number
We really want to involve these placeholders in the string so the ideal variable replaces them in the subsequent string as for the information kind of factor.
The factors are should introduce following a string followed by the % rate sign.
Program:
a='Hello'
b=25
c=3.21
print("The worth of an is %s"%a)
print("The worth of b is %d"%b)
print("The worth of c is %f"%c)
print("The hexadecimal worth of b is 0x%x"%b)
print("The Octal worth of b is %o"%b)
Output:
The worth of an is Hi
The worth of b is 25
The worth of c is 3.210000
The hexadecimal worth of b is 0x19
The Octal worth of b is 31
- From the above program, we can see that the factors of type String, Number and Float supplanted the placeholders %s, %d and %f in the string separately.
- Likewise, the number variable b changed over into hexadecimal and octal numbers utilizing the %x and %o placeholders
- If the string comprises of beyond what one organization specifier, we can remember the variable names for a tuple.
Model:
name='Ravi'
age=25
print("My name is %s and my age is %d" %(name,age))
Output:
I go by Ravi and my age is 25
- Here, the factors should follow the request for their placeholders. In any case, the translator raises TypeError.
- Now and again, to address the rates, we might have to print the rate sign followed by a whole number. By then, the % rate sign is utilized two times to get away.
Model:
result = "Ravi got 95"
print("%s%%" %result)
Output:
Ravi got 95%