Monday, April 21, 2025

String Formating in Python - .format() Example

a = 1
b = 10
c = 100

print('{} {} {}'.format(a, b, c))

This Python code assigns integer values to three variables a, b, and c respectively, and then prints their values in a formatted string to the console.

Here is a line-by-line explanation of the script:

a = 1
b = 10
c = 100

These lines declare three variables a, b, and c and assign them integer values of 1, 10, and 100, respectively.

print('{} {} {}'.format(a, b, c))

This line prints a formatted string to the console. The string contains three replacement fields (i.e., {}) that will be filled in with the values of a, b, and c, respectively. The format() method is used to substitute these values into the string.

The output of this script will be:

1 10 100

This is the formatted string where the values of a, b, and c have been substituted into the appropriate places.

Code Variant:


a = 1
b = 10
c = 100

print('First: {}, Second: {}, Third: {}'.format(a, b, c))

This line prints a formatted string to the console. The string contains three replacement fields (i.e., {}) that will be filled in with the values of a, b, and c, respectively. The format() method is used to substitute these values into the string. Additionally, each replacement field is preceded by a descriptive label separated by a colon, which is a common way to label the values when using string formatting.

The output of this script will be:

First: 1, Second: 10, Third: 100

This is the formatted string where the values of a, b, and c have been substituted into the appropriate places, and the labels for each value have been added.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...