format function in Python


Python | format() function
str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.

Syntax : { } .format(value)

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

Returntype : Returns a formatted string with the value passed as parameter in the placeholder position.

print ("Hello, I am {} years old !".format(18))
str = "This article is written in {}"
print (str.format("Python"))

Using Multiple Formatters :

Multiple pairs of curly braces can be used while formatting the string. Let’s say if another variable substitution is needed in sentence, can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders by 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 acces 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.

print ("Hi ! My name is {} and I am {} years old".format("User", 19))
print ("This is {} {} {} {}".format("one", "two", "three", "four"))

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 passes into the curly braces that serve as the placeholders in the original string.

Syntax : {0} {1}.format(positional_argument, keyword_argument)

Parameters : (positional_argument, keyword_argument)

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.

print("Every {3} should know the use of {2} {1} programming and {0}"
        .format("programmer", "Open", "Source", "Operating Systems"))

Type Specifying :

More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name:conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.

s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation

Syntax :

String {field_name:conversion} Example.format(value)

Errors and Exceptions :

ValueError : Error occurs during type conversion in this method.

print("The {0} of 100 is {1:b}" .format("binary", 100))

print("My average of this {0} was {1:.2f}%" .format("semester", 78.234876))

Padding Substitutions or Generating Spaces :

By default strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon.
<   :  left-align text in the field
^   :  center text in the field
>   :  right-align text in the field

print("{:*^20s}".format("Piyush"))




format
The format you want to format the value into.
Legal values:
'<' - Left aligns the result (within the available space)
'>' - Right aligns the result (within the available space)
'^' - Center aligns the result (within the available space)
'=' - Places the sign to the left most position
'+' - Use a sign to indicate if the result is positive or negative
'-' - Use a sign for negative values only
' ' - Use a leading space for positive numbers
',' - Use a comma as a thousand separator
'_' - Use a underscore as a thousand separator
'b' - Binary format
'c' - Converts the value into the corresponding unicode character
'd' - Decimal format
'e' - Scientific format, with a lower case e
'E' - Scientific format, with an upper case E
'f' - Fix point number format
'F' - Fix point number format, upper case
'g' - General format
'G' - General format (using a upper case E for scientific notations)
'o' - Octal format
'x' - Hex format, lower case
'X' - Hex format, upper case
'n' - Number format
'%' - Percentage format

Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes