format string python

Python Format String Method-: Python strings have powerful text-processing features, including searching and replacing, trimming characters, and changing case.Strings are immutable they can not be changed in place.Operations that appear to change strings actually return a copy with the changes.

We know that this is the part of string. we can format strings in Python 3 in two ways. The newer way is to use the string class’s format method. The format method combines a format string containing replacement fields marked with { } with replacement values taken from the parameters given to the format command.

If we need to include a literal { or } in the string we double it to {{ or }}. The format command is a powerful string-formatting mini-language that offers almost endless possibilities for manipulating string formatting.

It is fairly simple to use for the most common use cases. We need to use the more advanced options we can refer to the string-formatting section of the standard library documentation.

Format method and positional parameters-: A simple way to use the string format method is with numbered replacement fields that correspond to the parameters passed to the format function as like

>>> "{0} is the {1} of {2}".format("apple", "food", "the gods")     1
'apple is the food of the gods'
>>> "{{mango}} is the {0} of {1}".format("food", "the gods")        2
'{mango} is the food of the gods'

In the format method is applied to the format string which can also be a string variable 1. Doubling the { } characters escapes them so that they do not mark a replacement field 2.

This example has three replacement fields, {0}, {1}, and {2}, which are in turn filled by the first, second, and third parameters. No matter where in the format string you place {0}, it’s always be replaced by the first parameter, and so on. we can also use the named parameters.

format method and named parameters-: The format method also recognizes named parameters and replacement fields as like here

>>> "{fruit} is the food of {user}".format(fruit="mango",
...       user="the gods")
'mango is the fruit of the gods'

In the replacement parameter is chosen by matching the name of the replacement field with the name of the parameter given to the format command.

we can also use both positional and named parameters and we can even access attributes and elements within those parameters as like

>>> "{0} is the food of {user[1]}".format("Ambrosia",
...          user=["men", "the gods", "others"])
'Ambrosia is the food of the gods'


Format specifiers-: Format specifiers let us specify the result of the formatting with even more power and control than the formatting sequences of the older style of string formatting. The format specifier lets us control the fill character, alignment, sign, width, precision, and type of the data when it is substituted for the replacement field. As noted earlier in the syntax of format specifiers is a mini-language in its own right and too complex to cover completely here, but the following examples give us an idea of its usefulness as like

>>> "{0:10} is the food of gods".format("Ambrosia")                       1
'Ambrosia   is the food of gods'
>>> "{0:{1}} is the food of gods".format("Ambrosia", 10)                  2
'Ambrosia   is the food of gods'
>>> "{food:{width}} is the food of gods".format(food="Ambrosia", width=10)
'Ambrosia   is the food of gods'
>>> "{0:>10} is the food of gods".format("Ambrosia")                      3
'  Ambrosia is the food of gods'
>>> "{0:&>10} is the food of gods".format("Ambrosia")                     4
'&&Ambrosia is the food of gods'

Formatting String With % -: It covers formatting strings with the string modulus (%) operator. This operator is used to combine Python values into formatted strings for printing or other use. C users will notice a strange similarity to the printf family of functions. The use of % for string formatting is the old style of string formatting and  cover it here because it was the standard in earlier versions of Python and we are likely to see it in code that has been ported from earlier versions of Python or was written by coders who are familiar with those versions. This style of formatting should not be used in new code however  it is slated to be deprecated and then removed from the language in the future. as like..

>>> "%s is the %s of %s" % ("Ambrosia", "food", "the gods")
'Ambrosia is the food of the gods'

The string modulus operator takes two parts First is  the left side which is a string and second is the right side which is a tuple. The string modulus operator scans the left string for special formatting sequences and produces a new string by substituting the values on the right side for those formatting sequences, in order. In this example, the only formatting sequences on the left side are the three instances of %s, which stands for “Stick a string in here.”

>>> "%s is the %s of %s" % ("Nectar", "drink", "gods")
'Nectar is the drink of gods'
>>> "%s is the %s of the %s" % ("Brussels Sprouts", "food",...   "foolish")
'Brussels Sprouts is the food of the foolish'

Using formatting sequences-: All formatting sequences are sub-strings contained in the string on the left side of the central %. Each formatting sequence begins with a percent sign and is followed by one or more characters that specify what is to be substituted for the formatting sequence and how the substitution is to be accomplished.

The %s formatting sequence used previously is the simplest formatting sequence. it indicates that the corresponding string from the tuple on the right side of the central % should be substituted in place of the %s.

Other formatting sequences can be more complex. The following sequence specifies the field width (total number of characters) of a printed number to be six, specifies the number of characters after the decimal point to be two, and left-justifies the number in its field.

Named parameters and formatting sequences-:  one additional feature available with the % operator can be useful in certain circumstances. Unfortunately It describe.  I have to employ a Python feature that I have not yet discussed in detail.  dictionaries, commonly called hash tables or associative arrays in other languages.

Formatting sequences can specify what should be substituted for them by name rather than by position. When we do this each formatting sequence has a name in parentheses immediately following the initial % of the formatting sequence like this ..

"%(pi).2f"              1

1 Note name in parentheses.
In the argument to the right of the % operator is no longer given as a single value or tuple of values to be printed  but as a dictionary of values to be printed with each named formatting sequence having a correspondingly named key in the dictionary. Using the previous formatting sequence with the string modulus operator we might produce code like this

>>> num_dict = {'e': 2.718, 'pi': 3.14159}
>>> print("%(pi).2f - %(pi).4f - %(e).2f" % num_dict)
3.14 - 3.1416 - 2.72



Leave a Reply

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