Convert a value to a formatted string
#!/usr/bin/python
d = format(123456, '10,d') # use seperator
print(d)
n = format(3.1415925, '3.2f') # set precision
print(type(n), n)
s = format('Hello', '>10s') # right align
print(s, '|')
#!/usr/bin/python
# string
str = "String: %s %s" % ('One', 'Two');
str = "String: %10s %10s" % ('One', 'Two'); # One Two
str = "String: %-10s %-10s" % ('One', 'Two'); #One Two
str = "String: %10.2s %10.2s" % ('One', 'Two'); # On Tw
# number
str = "Number: %d %f" % (10, 3.14); # 10 3.140000
str = "Number: %10d %10.2f" % (10, 3.14); # 10 3.14
str = "Number: %010d %010.2f" % (10, 3.14) #0000000010 0000003.14
# named placeholder
d = {'name':'Lin', 'age':37};
str = "%(name)s %(age)d" % d;
[[fill]align][sign][#][0][width][grouping_option][.precision][type]
#!/usr/bin/python
# string
str = "String: {} {}".format('One', 'Two'); #One Two
str = "String: {1} {0}".format('One', 'Two'); #Two One
str = "String: {:>10} {:>10}".format('One', 'Two'); # One Two
str = "String: {:^10} {:^10}".format('One', 'Two'); # One Two
str = "String: {:<10} {:<10}".format('One', 'Two'); #One Two
str = "String: {:_<10} {:_<10}".format('One', 'Two'); #One_______ Two_______
str = "Integer: {:_=+10} {:_=+10}".format(10, 100); #One_______ Two_______
print(str)
str = "String: {:>10.2} {:>10.2}".format('One', 'Two'); # On Tw
# number
str = "Number: {:d} {:f}".format(10, 3.14); # 10 3.140000
str = "Number: {:10d} {:10.2f}".format(10, 3.14); # 10 3.14
str = "Number: {:010d} {:010.2f}".format(10, 3.14) #0000000010 0000003.14
# named placeholder
d = {'name':'Lin', 'age':37};
str = "{name} {age}".format(**d);
# accessing arguments by name
str = 'Name: {fname}, {lname}'.format(fname='Lin', lname='Chen')
print(str)
# converting the value to different bases
str = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
print(str)