深度阅读

What does %s do in Python? The Difference Between %s and %d in Python?

作者
作者
2023年08月22日
更新时间
17.96 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。