What is the operation for string formatting in Python?

In Python, string formatting can be done by using the format() method of strings or by using the % operator to insert variables into strings. Here are two examples of string formatting techniques.

Use the format() method:

name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old".format(name, age)
print(sentence)

Using the % operator:

name = "Bob"
age = 25
sentence = "My name is %s and I am %d years old" % (name, age)
print(sentence)

You can choose either of these two methods to perform string formatting operations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds