Teachnique
      CourseRoadmaps
      Login

      OverviewCommentsUser InputNumbersBooleansHistoryHello World ProgramEnvironment SetupSyntaxVariablesData TypesType CastingUnicode SystemLiteralsOperators

      Control FlowBreak StatementContinue StatementPass StatementNested LoopsDecision MakingIf StatementIf-else StatementNested IF StatementMatch-Case StatementLoopsFor LoopsFor-else LoopsWhile Loops

      FunctionsBuilt-in FunctionsDefault ArgumentsKeyword ArgumentsKeyword-Only ArgumentsPositional ArgumentsPositional-Only ArgumentsArbitrary ArgumentsVariable ScopeFunction AnnotationsModules

      StringSlicing StringsModify StringsString ConcatenationString FormattingEscape CharactersString MethodsString Exercises

      ListsList ExercisesAccess List ItemsChange List ItemsAdd List ItemsRemove List ItemsLoop ListsList ComprehensionSort ListsCopy ListsJoin ListsList Methods

      TuplesAccess Tuple ItemsUpdate TuplesUnpack Tuple ItemsLoop TuplesJoin TuplesTuple MethodsTuple Exercises

      SetsAccess Set ItemsAdd Set ItemsRemove Set ItemsLoop SetsJoin SetsCopy SetsSet OperatorsSet MethodsSet Exercises

      DictionariesDictionary ExercisesAccess Dictionary ItemsChange Dictionary ItemsAdd Dictionary ItemsRemove Dictionary ItemsDictionary View ObjectsLoop DictionariesCopy DictionariesNested DictionariesDictionary Methods

      ArraysAccess Array ItemsAdd Array ItemsRemove Array ItemsLoop ArraysCopy ArraysReverse ArraysSort ArraysJoin ArraysArray MethodsArray Exercises

      File HandlingWrite to FileRead FilesRenaming and Deleting FilesDirectoriesFile Methods

      OOP ConceptsDynamic BindingDynamic TypingAbstractionObject and ClassesEncapsulationInterfacesPackagesInner ClassesAnonymous Class and ObjectsSingleton ClassWrapper ClassesEnumsReflectionClass AttributesClass MethodsStatic MethodsConstructorsAccess ModifiersInheritancePolymorphismMethod OverridingMethod Overloading

      Feedback

      Submit request if you have any questions.

      Course
      String Formatting

      Python Tutorial

      This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.

      String Formatting

      String formatting is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python's string concatenation operator doesn't accept a non-string operand. Hence, Python offers following string formatting techniques −
      • Using % operator for substitution
      • Using format() method of str class
      • Using f-string syntax
      • Using String Template class

      Formatting Operator %

      One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Format specification symbols (%d %c %f %s etc) used in C language are used as placeholders in a string.
      Following is a simple example
      print ("My name is %s and weight is %d kg!" % ('Zara', 21))
      It will produce the following output
      My name is Zara and weight is 21 kg!
      Here is the list of complete set of symbols which can be used along with %
      Sr.No
      Format Symbol & Conversion
      1
      %c
      character
      2
      %s
      string conversion via str() prior to formatting
      3
      %i
      signed decimal integer
      4
      %d
      signed decimal integer
      5
      %u
      unsigned decimal integer
      6
      %o
      octal integer
      7
      %x
      hexadecimal integer (lowercase letters)
      8
      %X
      hexadecimal integer (UPPERcase letters)
      9
      %e
      exponential notation (with lowercase 'e')
      10
      %E
      exponential notation (with UPPERcase 'E')
      11
      %f
      floating point real number
      12
      %g
      the shorter of %f and %e
      13
      %G
      the shorter of %f and %E
      Other supported symbols and functionality are listed in the following table
      Sr.No.
      Format Symbol & Conversion
      1
      *
      argument specifies width or precision
      2
      -
      left justification
      3
      +
      display the sign
      4
      <sp>
      leave a blank space before a positive number
      5
      #
      add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
      6
      0
      pad from left with zeros (instead of spaces)
      7
      %
      '%%' leaves you with a single literal '%'
      8
      (var)
      mapping variable (dictionary arguments)
      9
      m.n.
      m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)
      In the following example, name is a string and age is an integer variable. Their values are inserted in the string at %s and %d format specification symbols respectively. These symbols are interpolated to values in a tuple in front % operator.
      name="Rajesh"
      age=23
      print ("my name is %s and my age is %d years" % (name, age))
      It will produce the following output
      my name is Rajesh and my age is 23 years
      You can specify width of an integer and float object. Here integer objects a,b and c will occupy width of 5 characters in formatted string. Additional spaces will be padded to left.
      a=1
      b=11
      c=111
      print ("a=%5d b=%5d c=%5d" % (a, b, c))
      It will produce the following output
      a= 1 b= 11 c= 111
      In following example, width of float variable is specified to have 6 characters with three digits after decimal point.
      name="Rajesh"
      age=23
      percent=55.50
      print ("my name is %s, age %d and I have scored %6.3f percent marks" % (name, age, percent))
      It will produce the following output
      my name is Rajesh, age 23 and I have scored 55.500 percent marks
      Width for a string can also be specified. Default alignment is right. For left alignment give negative sign to width.
      name='TutorialsPoint'
      print ('Welcome To %20s The largest Tutorials Library' % (name, ))
      print ('Welcome To %-20s The largest Tutorials Library' % (name, ))
      It will produce the following output
      Welcome To TutorialsPoint The largest Tutorials Library
      Welcome To TutorialsPoint The largest Tutorials Library
      Add a '. ' to the format to truncate longer string.
      name='TutorialsPoint'
      print ('Welcome To %.5s The largest Tutorials Library' % (name, ))
      It will produce the following output
      Welcome To Tutor The largest Tutorials Library

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      Formatting Method format()

      This method of in-built string class provides ability to do complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant. The general syntax of format() method is as follows

      Syntax

      str.format(var1, var2,...)

      Return value

      The method returns a formatted string.
      The string itself contains placeholders {} in which values of variables are successively inserted.

      Example 1

      name="Rajesh"
      age=23
      print ("my name is {} and my age is {} years".format(name, age))
      It will produce the following output
      my name is Rajesh and my age is 23 years
      You can use variables as keyword arguments to format() method and use the variable name as the placeholder in the string.
      print ("my name is {name} and my age is {age} years".format(name="Rajesh", age=23))
      You can also specify C style formatting symbols. Only change is using ":" instead of %. For example, instead of %s use {:s} and instead of %d use {:d}
      name="Rajesh"
      age=23
      print ("my name is {:s} and my age is {:d} years".format(name, age))
      Precision formatting of numbers can be accordingly done.
      name="Rajesh"
      age=23
      percent=55.50
      print ("my name is {:s}, age {:d} and I have scored {:6.3f} percent marks".format(name, age, percent))
      It will produce the following output
      my name is Rajesh, age 23 and I have scored 55.500 percent marks
      String alignment is done with <, > and ^ symbols (for left, right and center alignment respectively) in place holder. Default is left alignment.
      name='TutorialsPoint'
      print ('Welcome To {:>20} The largest Tutorials Library'.format(name))
      print ('Welcome To {:<20} The largest Tutorials Library'.format(name))
      print ('Welcome To {:^20} The largest Tutorials Library'.format(name))
      It will produce the following output 
      Welcome To TutorialsPoint The largest Tutorials Library
      Welcome To TutorialsPoint The largest Tutorials Library
      Welcome To TutorialsPoint The largest Tutorials Library
      Similarly, to truncate the string use a "." in the place holder.
      name='TutorialsPoint'
      print ('Welcome To {:.5} The largest Tutorials Library'.format(name))
      It will produce the following output
      Welcome To Tutor The largest Tutorials Library

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.
      

      f-string Formatting

      The string starts with a 'f' prefix, and one or more place holders are inserted in it, whose value is filled dynamically.
      name = 'Rajesh'
      age = 23
      fstring = f'My name is {name} and I am {age} years old'
      print (fstring)
      It will produce the following output
      My name is Rajesh and I am 23 years old
      The f-string may contain expressions inside the {} placeholder.
      price = 10
      quantity = 3
      fstring = f'Price: {price} Quantity : {quantity} Total : {price*quantity}'
      print (fstring)
      It will produce the following output
      Price: 10 Quantity : 3 Total : 30
      The placeholders can be populated by dictionary values.
      user = {'name': 'Ramesh', 'age': 23}
      fstring = f"My name is {user['name']} and I am {user['age']} years old"
      print (fstring)
      It will produce the following output
      My name is Ramesh and I am 23 years old
      The = character is used for self debugging the expression in f-string.
      price = 10
      quantity = 3
      fstring = f"Total : {price*quantity=}"
      print (fstring)
      It will produce the following output
      Total : price*quantity=30
      It is also possible to call a user defined function inside the f-string expression.
      def total(price, quantity):
      return price*quantity
      
      price = 10
      quantity = 3
      
      fstring = f'Price: {price} Quantity : {quantity} Total : {total(price, quantity)}'
      print (fstring)
      It will produce the following output
      Price: 10 Quantity : 3 Total : 30
      Python f-strings also support formatting floats with precision specifications, as done by format() method and string formatting operator %
      name="Rajesh"
      age=23
      percent=55.50
      
      fstring = f"My name is {name} and I am {age} years old and I have scored {percent:6.3f} percent marks"
      print (fstring)
      It will produce the following output
      My name is Rajesh and I am 23 years old and I have scored 55.500 percent marks
      For string variable, you can specify the alignment just as we did with format() method and formatting operator %.
      name='TutorialsPoint'
      fstring = f'Welcome To {name:>20} The largest Tutorials Library'
      print (fstring)
      
      fstring = f'Welcome To {name:<20} The largest Tutorials Library'
      print (fstring)
      
      fstring = f'Welcome To {name:^20} The largest Tutorials Library'
      print (fstring)
      It will produce the following output
      Welcome To TutorialsPoint The largest Tutorials Library
      Welcome To TutorialsPoint The largest Tutorials Library
      Welcome To TutorialsPoint The largest Tutorials Library
      The f-strings can display numbers with hexadecimal, octal and scientific notation
      num= 20
      fstring = f'Hexadecimal : {num:x}'
      print (fstring)
      
      fstring = f'Octal :{num:o}'
      print (fstring)
      
      fstring = f'Scientific notation : {num:e}'
      print (fstring)
      It will produce the following output
      Hexadecimal : 14
      Octal :24
      Scientific notation : 2.000000e+01

      String Template Class

      The Template class in string module provides an alternative method to format the strings dynamically. One of the benefits of Template class is to be able to customize the formatting rules.
      The implementation of Template uses regular expressions to match a general pattern of valid template strings. A valid template string, or placeholder, consists of two parts: The $ symbol followed by a valid Python identifier.
      You need to create an object of Template class and use the template string as an argument to the constructor.
      Next call the substitute() method of Template class. It puts the values provided as the parameters in place of template strings.

      Example

      from string import Template
      
      temp_str = "My name is $name and I am $age years old"
      tempobj = Template(temp_str)
      ret = tempobj.substitute(name='Rajesh', age=23)
      print (ret)
      It will produce the following output
      My name is Rajesh and I am 23 years old
      We can also unpack the key-value pairs from a dictionary to substitute the values.
      from string import Template
      
      student = {'name':'Rajesh', 'age':23}
      temp_str = "My name is $name and I am $age years old"
      tempobj = Template(temp_str)
      ret = tempobj.substitute(**student)
      
      print (ret)
      It will produce the following output
      My name is Rajesh and I am 2
      3 years old

      Practice with Online Editor

      Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
      Remember to save code(Ctrl + S Or Command + S) before run it.