String Format() in Python Example
A simple demonstration of Python String format() Method in Python.
Python3
name = "Ram" age = 22 message = "My name is { 0 } and I am { 1 } years \ old. { 1 } is my favorite \ number.". format (name, age) print (message) |
Output
My name is Ram and I am 22 years old. 22 is my favorite number.
Using .Format() Method
This method of the built-in string class provides functionality for complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant. The general syntax of format() method is string.format(var1, var2,…). Here we will try to understand how to Format A String That Contains Curly Braces In Python.
Python3
txt = "I have {an:.2f} Rupees!" print (txt. format (an = 4 )) |
Output
I have 4.00 Rupees!
Using a Single Formatter
In this example, we will use the string bracket notation program to demonstrate the str. format() method. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format().
Python3
# using format option in a simple string print ( "{}, A computer science portal for geeks." . format ( "w3wiki" )) # using format option for a # value stored in a variable str = "This article is written in {}" print ( str . format ( "Python" )) # formatting a string using a numeric constant print ( "Hello, I am {} years old !" . format ( 18 )) |
Output
w3wiki, A computer science portal for geeks.
This article is written in Python
Hello, I am 18 years old!
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.