Python 3 Tutorial
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 --> 30Seperator 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
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
>>>"name is %s age is %s"%('sam',45) name is sam age is 45
>>>"name is {} age is {}".format('sam',45) name is sam age is 45
"....%s...." % (values)
"....{}....".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 targetsNote: 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 20Mixing Position and Keywords
>>> "{city},{country} temperature {0}C".format(32.3,city='New Delhi',country='INDIA') 'New Delhi,INDIA temperature 32.3C'
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