Welcome

sampleqa.in tutorials, Python Programming  tutorial

Python 3 Tutorial


Python Print and Format methods


Python print function usage

print method outputs its content to standard output device(stdout).
print([object [, object]*]
[, sep=' '] [, end='\n']
[, file=sys.stdout] [, flush=False])

object: Any type of objects can be passed to print function
sep seperates each object by space
end at the end of the printing,cursor moves to next line
file usually or by default,it outputs to standard output device(stdout), user can redirect to file also
flush flushes the stream       
      
      	print single value
      	
      	print("hello");  #hello
      	
	print multiple values, each object seperated by space
      	
      	print("hello","world")  #hello world
      	print("hello","world","!") #hello world !
      	
      	x=10;y=20;
      	print(x,y,'-->',x+y) #10 20 --> 30
      
Seperator is colon(:)
>>> print("City","New York",sep=":")
City:New York
      

In above example, we have two string objects,each object is seperated by colon(:)

End(of the printing) is space(' ')
>>> for i in range(1,11):
       print(i, end=' ')
       
     1 2 3 4 5 6 7 8 9 10 >>> 

      

In above example, printing number from 1 to 10 , by default end is newline character(\n), to override that passing space to end argument. It prints all numbers in the same line, otherwise line by line

Python format function usage

     Converts an value Object to a formatted representation

		format(value, formatspec)
	
	format(1.33333,'.2f') --> 1.33
	"{0:.2f}".format(1.33333) --> 1.33
	"{0:.3f} {1:.1f}".format(1.3333,1.3333) ---> 1.333,1.3
	

Formatting method Syntax

    

Format expression using Substitution.

		>>>"name is %s age is %s"%('sam',45)
		name is sam age is 45
	

Using format method

		>>>"name is {} age is {}".format('sam',45)
		name is sam age is 45
	

Python String Formatting

  • String Formatting Expressions(old-style)
  • String Formatting Method call(new-style)

String Formatting Expressions(old-style)

"....%s...." % (values)

String Formatting Method call(new-style)

"....{}....".format(values)

    format method available from python 2.6 onwards. It uses template as subject and any number arguments that represents values to be substituted according to the template

Curly Braces designates substitution targets
  1. "{} {} {}".format(val1,val2,val3) --- Relative Position
  2. "{0} {1} {2}".format(val1,val2,val3)--- By Position
  3. "{name1} {name2} {name3}".format(val1,val2,val3)---- By Keyword

Note: Option 2 and Option 3 are flexible ,because arguments order can be changed according to your needs

		"{} {} {}".format(10,20,30)  # 10 20 30
		"{3} {1} {2}".format(10,20,30)  # 30 10 20
		"{num1} {num3} {num2}".format(num1=10,num2=20,num3=30)  #  10  30 20
	
Mixing Position and Keywords
>>> "{city},{country} temperature {0}C".format(32.3,city='New Delhi',country='INDIA')
'New Delhi,INDIA temperature 32.3C'


Looking up values with in the Object

     format string syntax allows us to refer to portion of any object. Object has attributes, those attribute names can be referenced in the format string,format method replaces with object values.

To reference an attribute,seperate its name from the object reference with a period.

for example: Object has attributes attr1,attr2, "{0.attr1}, {0.attr2}".format(obj)

format time object
	#	time class located in datetime module
	
	import datetime
	
	t = datetime.time(hour=12,minute=30,second=26)
	
	"Time is {0.hour}:{0.minute}:{0.second}".format(t)
	Time is 12:30:26
	
	time object t has various fields, like hour,minute,seconds,min,max,microsecond, 
		above example uses hour,minute,second. names should match
	

ADS