Tuesday, May 22, 2018

String Formatting

String formatting is important in any programming language below are 
some sample examples in python, these examples are covering most the string 
formatting in python.


bld_no = 200
print("I live in building " +"P"+str(bld_no))

Output : I live in building P200

# replacement fields
print("I live in building P{0}".format(bld_no))

Output : I live in building P200

print("There are {0} days in the month {1}, {2}, {3}, {4}, {5}, {6}, {7}
       ".format(31, "Jan","Mar","May","Jul","Aug","Oct","Dec" ))
Output : There are 31 days in the month Jan, Mar, May, Jul, Aug, Oct, Dec

print("Jan: {2} Feb: {0} Mar: {2} Apr: {1}"      "May - {2} Jun - {1} Jul - {2} Aug {2} Sep {1}"      "Oc - {2} Nav - {1} Dec - {2}".format(28,30,31))
Output : Jan: 31 Feb: 28 Mar: 31 Apr: 30May - 31 Jun - 30 Jul - 31 Aug 31 Sep 30Oc - 31 Nav - 30 Dec - 31
print("I live in building P %d" %bld_no)

Output : I live in building P237
print("I live in building P %d at %d floor near %s" %(bld_no,1,"albany dr")) 

Output : I live in building P 200 at 1 floor near albany dr
data = "1:A, 2:B, 3:C, 4:D, 5:E, 6:F, 7:G, 8:H"print(data[::5])

Output : 12345678

No comments:

Post a Comment

Program to check valid IP addresses