What does format do in python

Python String format() Method

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 statement every time we use the concept of formatting.

Python3

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.

A simple demonstration of Python String 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(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function.

Syntax of string format() function

Syntax: < >.format(value)

Parameters:

  • value : Can be an integer, floating point numeric constant, string, characters or even variables.

Using a Single Formatter

In this example, we will use the string bracket notation program to demonstrate the str.format() method.

Python3

GeeksforGeeks, A computer science portal for geeks. This article is written in Python Hello, I am 18 years old!

String format() with multiple placeholders

Multiple pairs of curly braces can be used while formatting the string in Python. Let’s say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order.

Syntax : < > < >.format(value1, value2)

Parameters : (value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string.

Errors and Exceptions :

IndexError : Occurs when string has an extra placeholder, and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3…. to access the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError.

Python program using multiple placeholders to demonstrate str.format() method.

Python3

GeeksforGeeks, is a computer science portal for geeks Hi! My name is User and I am 19 years old This is one two three four

String format() IndexError

Python program demonstrating Index error number of placeholders is four but there are only three values passed.

Python3

IndexError: tuple index out of range

Formatting Strings using Escape Sequences

You can use two or more specially designated characters within a string to format a string or perform a command. These characters are called escape sequences. An Escape sequence in Python starts with a backslash (\). For example, \n is an escape sequence in which the common meaning of the letter n is literally escaped and given an alternative meaning – a new line.

Escape sequence Description Example
\n Breaks the string into a new line print(‘I designed this rhyme to explain in due time\nAll I know’)
\t Adds a horizontal tab print(‘Time is a \tvaluable thing’)
\\ Prints a backslash print(‘Watch it fly by\\as the pendulum swings’)
\’ Prints a single quote print(‘It doesn\’t even matter how hard you try’)
\” Prints a double quote print(‘It is so\”unreal\”‘)
\a makes a sound like a bell print(‘\a’)

Formatters with Positional and Keyword Arguments

When placeholders are empty, Python will replace the values passed through str.format() in order. The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passed into the curly braces that serve as the placeholders in the original string.

  • Positional_argument can be integers, floating point numeric constants, strings, characters and even variables.
  • Keyword_argument is essentially a variable storing some value, which is passed as parameter.

To demonstrate the use of formatters with positional key arguments.

Источник

Python String format() Method

Insert the price inside the placeholder, the price should be in fixed point, two-decimal format:

txt = «For only dollars!»
print(txt.format(price = 49))

Definition and Usage

The format() method formats the specified value(s) and insert them inside the string’s placeholder.

The placeholder is defined using curly brackets: <>. Read more about the placeholders in the Placeholder section below.

The format() method returns the formatted string.

Syntax

Parameter Values

Parameter Description
value1, value2. Required. One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The Placeholders

The placeholders can be identified using named indexes , numbered indexes , or even empty placeholders <> .

Example

Using different placeholder values:

txt1 = «My name is , I’m «.format(fname = «John», age = 36)
txt2 = «My name is , I’m «.format(«John»,36)
txt3 = «My name is <>, I’m <>«.format(«John»,36)

Formatting Types

Inside the placeholders you can add a formatting type to format the result:

: Try it Left aligns the result (within the available space)
:> Try it Right aligns the result (within the available space)
:^ Try it Center aligns the result (within the available space)
:= Try it Places the sign to the left most position
:+ Try it Use a plus sign to indicate if the result is positive or negative
:- Try it Use a minus sign for negative values only
: Try it Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers)
:, Try it Use a comma as a thousand separator
:_ Try it Use a underscore as a thousand separator
:b Try it Binary format
:c Converts the value into the corresponding unicode character
:d Try it Decimal format
:e Try it Scientific format, with a lower case e
:E Try it Scientific format, with an upper case E
:f Try it Fix point number format
:F Try it Fix point number format, in uppercase format (show inf and nan as INF and NAN )
:g General format
:G General format (using a upper case E for scientific notations)
😮 Try it Octal format
😡 Try it Hex format, lower case
:X Try it Hex format, upper case
:n Number format
:% Try it Percentage format

Источник

Читайте также:  Java php ruby net
Оцените статью