Different types of Python String Formatting
-
String Formatting is the easiest way of combining multiple values to a string. The advantage here is that we can easily combine different datatypes to the string in different formats. Doing the same using the '+' symbol makes it difficult to read and is prone to unexpected errors.
To insert some content to a string, we can use {} as place holders. Within bracket provide name or index. Format type option can be provided as second parameter. Some common formats are decimal(:d), number(:n), percentage(:%). Number of decimal places to display can be indicated after :.
Copieds1 = "String with 2 values: {0} and {1}".format("One", 2) s2 = "String with 2 values: {first} and {second}".format(first ="One", second =2) print (s1) print (s2) marksPercent = "Marks Percent is {:.1%}" print(marksPercent.format(0.7522))
String with 2 values: One and 2
String with 2 values: One and 2
Marks Percent is 75.2%We will go through different formatting types in detail below.
-
Percentage Format
We can format a given number to percentage as below. Output value is provided number multiplied by 100. We can manage number of decimal places to display as well.
Copiednum = .825 str1 = "Percentage is {:%}" print(str1.format(num)) str1 = "Percentage to 2 decimal places is {:.2%}" print(str1.format(num)) str1 = "Percentage to 0 decimal places is {:.0%}" print(str1.format(num))
Percentage is 82.500000%
Percentage to 2 decimal places is 82.50%
Percentage to 0 decimal places is 82% -
Decimal Format
Convert numbers in any other format to decimal format.
Copied#Binary to decimal num = 0b10101 str1 = "Decimal number is {:d}" print(str1.format(num)) #Octact to decimal num = 0O10101 str1 = "Decimal number is {:d}" print(str1.format(num)) #Hexadecimal to decimal num = 0x10101 str1 = "Decimal number is {:d}" print(str1.format(num))
Decimal number is 21
Decimal number is 4161
Decimal number is 65793 -
Fix Point Number Format
Convert numbers in any format to floating point numbers. Number of digits after decimal point can also be mentioned.
Copiednum = 0b10101 str1 = "Fixed point number is {:f}" print(str1.format(num)) num = 20 str1 = "Fixed point number by 2 decimals is {:.2f}" print(str1.format(num)) str1 = "Fixed point number by 0 decimals is {:.0f}" print(str1.format(num))
Fixed point number is 21.000000
Fixed point number by 2 decimals is 20.00
Fixed point number by 0 decimals is 20 -
Binary Format
Convert numbers in any format to binary number.
Copied#Decimal to binary num = 50 str1 = "Binary number is {:b}" print(str1.format(num)) #Octact to binary num = 0O10101 str1 = "Binary number is {:b}" print(str1.format(num)) #Hexadecimal to binary num = 0x10101 str1 = "Binary number is {:b}" print(str1.format(num))
Binary number is 110010
Binary number is 1000001000001
Binary number is 10000000100000001 -
Scientific Format
Convert numbers in any format to scientific format. E to display characters in upper case and e for lower case.
Copied#Decimal to scientific num = 50 str1 = "Scientific number is {:e}" print(str1.format(num)) #Octact to scientific num = 0O10101 str1 = "Scientific number is {:E}" print(str1.format(num)) #Hexadecimal to scientific num = 0x10101 str1 = "Scientific number is {:e}" print(str1.format(num))
Scientific number is 5.000000e+01
Scientific number is 4.161000E+03
Scientific number is 6.579300e+04 -
Octal Format
Convert numbers to octal format.
Copied#Decimal to octal num = 50 str1 = "Octal number is {:o}" print(str1.format(num)) #Hexadecimal to octal num = 0x10101 str1 = "Octal number is {:o}" print(str1.format(num))
Octal number is 62
Octal number is 200401 -
Provide space and align values
Used to provide space before, after or around the inserted value.
Three options there.:<20Value placed and after that 20 spaces provided.
:>2020 spaces provided and then value placed.
:^2010 spaces provided on the left and right.
Copied#Left align num = 50 str1 = "Left aligned number {:<20} inserted" print(str1.format(num)) #Right align num = 50 str1 = "Right aligned number {:>20} inserted" print(str1.format(num)) #Center align num = 50 str1 = "Center aligned number {:^20} inserted" print(str1.format(num))
Left aligned number 50 inserted
Right aligned number 50 inserted
Center aligned number 50 inserted -
Thousand Separator
Provide separators , or _ for bigger numbers.
Copied#Comma separator num = 500000000 str1 = "Comma separated number {:,}" print(str1.format(num)) #Underscore separator str1 = "Underscore separated number {:_}" print(str1.format(num))
Comma separated number 500,000,000
Underscore separated number 500_000_000
-
Signing a Number
Used to indicate -ve or +ve numbers.
:=Provide a mentioned space between sign and number. Sign displayed only for negative numbers.
:+Shows the actual sign of the number.
:-Shows positive numbers without sign and negative numbers with sign.
Copiednum1 = +50 num2 = -100 str1 = "Signed numbers {:=10} and {:=20} with space added" print(str1.format(num1, num2)) str1 = "Signed numbers {:+} and {:+} added" print(str1.format(num1, num2)) str1 = "Signed numbers {:-} and {:-} added" print(str1.format(num1, num2))
Signed numbers 50 and - 100 with space added
Signed numbers +50 and -100 added
Signed numbers 50 and -100 added -
Apply Multiple Formats on Same Item
To apply multiple formats on the same item, we have to do it separate as below. Here we are trying to make a number fixed point and, provide comma separators also.
Copiednum = 1000000.44444 str11 = '{:.2f}'.format(num) print(str11) str1 = "Multiple formats applied on number {:,}" print(str1.format(float(str11)))
Multiple formats applied on number 1,000,000.44
-
Date Format
String formatting does not have an option to format dates directly. We will have to convert datetime object to string as below and then combine.
Refer Convert Datetime to String - All Formats for converting datetime object to string in different formats.
Copiedfrom datetime import datetime datetoconvert = datetime(2022, 1, 15, 20, 35, 45, 123456) stringdate = datetoconvert.strftime('%d-%b-%y') str1 = "Date is {}" print(str1.format(stringdate))
Date is 15-Jan-22