Type Specifying In Python
More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.
Using %s – string conversion via str() prior to formatting
Python3
print ( "%20s" % ( 'w3wiki' , )) print ( "%-20s" % ( 'Interngeeks' , )) print ( "%.5s" % ( 'Interngeeks' , )) |
Output
w3wiki
Interngeeks
Inter
Using %c– character prior to formatting
Python3
type = 'bug' result = 'troubling' print ('I wondered why the program was % s me. Then\ it dawned on me it was a % s .' % (result, type )) |
Output
I wondered why the program was troubling me. Thenit dawned on me it was a bug .
Using %i signed decimal integer and %d signed decimal integer(base-10) prior to formatting
Python3
match = 12000 site = 'Amazon' print (" % s is so useful. I tried to look\ up mobile and they had a nice one that cost % d rupees." % (site, match)) |
Output
Amazon is so useful. I tried to lookup mobile and they had a nice one that cost 12000 rupees.
Python String format() Method
The format()
method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.