String Formatting

Recommended by 0 users

Basic formatting

Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate.

Since the elements are not represented by something as descriptive as a name, this simple style should only be used to format a relatively small number of elements.

String formatting

Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder.

Python uses C-style string formatting to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”. ‘%’ is used with an argument specifically which tells what type of operation is to be carried out. % are the most commonly used directives. Python 2.6 introduced the str.format() method with a slightly different syntax of the existing  % operator.


Here is another way to use %s


Now, let’s have a look at some more format directives and their application:

-Formatting integer




  • number=’%i’%(4)
  • number

Output: ‘4’

-Format decimal integer same




  • number=’%d’%(4.84)
  • number


-Hexadecimal integer




  • hex_num=’%x’%(16)
  • hex_num

Output: ’10’





  • number=’%f’%(4)
  • number

Output: ‘4.000000’

The list doesn’t end here. There are some more directives :

%c – ASCII characters

%e – float exponent

%u – unsigned integer

%o – octal integer


Enroll for Instructor Led Live Python Training

0 Responses on String Formatting"

Leave a Message

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

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.