What does %s do in Python? The Difference Between %s and %d in Python?
Published on Aug. 22, 2023, 12:13 p.m.
In this article, we will see the difference between %s and %d in Python.
What does %s do in Python?
The % symbol is used in Python with a large variety of data types .It is used as an argument specifier and string formatter. %s specifically.It allows us to format a value.It is used to incorporate another string.It automatically provides type conversion.
The %s operator is put where the string is.The number of values specified in parentheses after the % operator at the end of the string value.
name = "Geek"
print("Hey, %s!" % name)
Outputs :
Hey, Geek!
What does %d do in Python?
The %d operator is used as a placeholder to specify values.The %d operator is put where the integer is.
num = 2021
print("%d is here!!" % num)
Output
2021 is here!!
How to Use %d in Python
The following code illustrates the usage of %d.
frac_num = 8/3
print("Rational number formatting using %d")
print("%d is equal to 8/3 using this operator." % frac_num)
dec_num = 10.9785
print("Decimal number formatting using %d")
print("%d is equal to 10.9785 using this operator." % dec_num)
Rational number formatting using %d
2 is equal to 8/3 using this operator.
Decimal number formatting using %d
10 is equal to 10.9785 using this operator.
Difference Between %s and %d?
It is used as a backup for string values. It is used to get rid of numeric values.Uses string conversion via str() before straining. Uses decimal conversion via intrapunturing before strangling.%s can accept numeric values also and it automatically does the type conversion. In case a string is specified for the %d operator, a type error is returned.