String Formatting


String Formatting

The format() is one of the formatting methods in the string datatype Python programming language, which allows a range of substitutions and formatting. This method enables us to concatenate elements within a string through positional formatting. Python uses the string formatting method similar to C-style string formatting to create new, formatted strings. The "%" operator usually is used to format a set of variables enclosed in a fixed size list(tuple), together with a format string, which will contain normal text along with "argument specifiers", special symbols like "%s" and "%”. The format () method is the most flexible and useful method in formatting strings. The parenthesis {} are used as the placeholder in the string and are also replaced by the format () method argument. Let's look at the given

Formatting Types:-

  • “ :< ” - Align the result to the left within the given space.
  • “ :> ” - Align the result to the right within the given space.
  • “ :^ ” - Align the result to the centre within the given space.
  • “ := ” - Align the result to the leftmost position within the given space.
  • “ :+ ” - Indicates the result is a positive or negative value.
  • “ :- ” - Indicates the result as a negative value.
  • “ : ” - Insert a space before values.
  • “ : , ” - Comma as a separator.
  • “ :_” - Use underscore as a comma for thousand values. (e.g., 1_000_000)
  • “ :b ” - Binary formatting.
  • “ :c ” - Unicode character.
  • “ :d ” - Decimal formatting.
  • “ :e ” - Power will represent in scientific format (e).
  • “ :E ” - Power will represent in scientific format (E).
  • “ :f ” - Fixpoint number default to 6 decimals zeros.
  • “ :F ” - Displays in Uppercase.
  • “ :g ” - General formatting.
  • “ :G ” - General Formatting with E.
  • “ :o ” - Convert into the octal format.
  • “ :x ” - Convert into a small hexadecimal number.
  • “ :X ” - Convert into upper case hexadecimal number.
  • “ :n ” - Number formatting.
  • “ :% ” - Percentage Formatting

Example:

name = "Kowledge2life" cl=2021 print(" The named %s is website since %d ." % (name, cl))

OUTPUT:

The named Kowledge2life is website since 2021 .