String format vs %

  • Exp:

cents = int(raw_input("Enter total cents: "))

quarters = cents // 25
cents = cents - quarters * 25

dimes = cents // 10
cents = cents - dimes * 10

nickels = cents // 5
pennies = cents - 5 * nickels

print"Your change is {0} quarters, {1} dimes, {2} nickels, and {3} pennies".format(quarters, dimes, nickels, pennies)
  • Method

age = 25  
name = 'Caroline'  

print('{0} is {1} years old. '.format(name, age)) #输出参数  
print('{0} is a girl. '.format(name))  
print('{0:.3} is a decimal. '.format(1/3)) #小数点后三位  
print('{0:_^11} is a 11 length. '.format(name)) #使用_补齐空位  
print('{first} is as {second}. '.format(first=name, second='Wendy')) #别名替换  
print('My name is {0.name}'.format(open('out.txt', 'w'))) #调用方法  
print('My name is {0:8}.'.format('Fred')) #指定宽度  
print "{0:.0f} kilometers\n{1:.0f} meters\n{2:.1f} centimeters".format(km, m, cm)   #用\n换行
print "I want to enter a super long line and it is time to change \
the line"    #用\接行


#output
Caroline is 25 years old.   
Caroline is a girl.   
0.333 is a decimal.   
_Caroline__ is a 11 length.   
Caroline is as Wendy.   
My name is out.txt  
My name is Fred. 

3 kilometers
221 meters
18.4 centimeter

I want to enter a super long line and it is time to change the line
Keep two decimals:
print "Total cost: {0:.2f}".format(total_cost)   #keep two decimals

Keep two decimals and as the same time align:

for x in numbers:
    print "{:10.4f}".format(x)


#output:
#   23.2300
#    0.1233
#    1.0000
#    4.2230
# 9887.2000

3.1415926 {:.2f} 3.14 保留小数点后两位

3.1415926 {:+.2f} +3.14 带符号保留小数点后两位

-1 {:+.2f} -1.00 带符号保留小数点后两位

2.71828 {:.0f} 3 不带小数

5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)

5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)

10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)

1000000 {:,} 1,000,000 以逗号分隔的数字格式

0.25 {:.2%} 25.00%百分比格式

1000000000 {:.2e} 1.00e+09指数记法

13 {:10d} 13右对齐 (默认, 宽度为10)

13 {:<10d} 13左对齐 (宽度为10)

13 {:^10d} 13中间对齐 (宽度为10)

  • Theory:

Python originally borrowed the % placeholder heavily from the C language. Since then, the language has evolved to include the .format method for strings. This method provides more powerful formatting options.

How to insert a variable into a string?

Python 2.6 introduced the str.format()method with a slightly different syntax from the existing%

operator.

#!/usr/bin/python
sub1 = "python string"
sub2 = "an arg"

a = "i am a %s %s" % (sub1, "!")
b = "i am a {0}".format(sub1)

c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2)

print a    # "i am a python string!"
print b    # "i am a python string"
print c    # "with an arg!"
print d    # "with an arg!"

Difference:

  • Something that the modulo operator ( % ) can't do, afaik:

    tu =(12, 45, 22222, 03, 6)
    print'{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
    

    result

    12 22222 45 22222 103 22222 6 22222
    

    Very useful.

  • Another point:format(), being a function, can be used as an argument in other functions:

  • li = [12,45,78,784,2,69,1254,4785,984]
    print map('the number is {}'.format,li)   
    
    print
    
    from datetime import datetime,timedelta
    
    once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
    delta = timedelta(days=13, hours=8,  minutes=20)
    
    gen =(once_upon_a_time +x*delta for x in xrange(20))
    
    print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
    
     Results in:
    
       ['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']

2010-07-01 12:00:00
2010-07-14 20:20:00
2010-07-28 04:40:00
2010-08-10 13:00:00
2010-08-23 21:20:00
2010-09-06 05:40:00
2010-09-19 14:00:00
2010-10-02 22:20:00
2010-10-16 06:40:00
2010-10-29 15:00:00
2010-11-11 23:20:00
2010-11-25 07:40:00
2010-12-08 16:00:00
2010-12-22 00:20:00
2011-01-04 08:40:00
2011-01-17 17:00:00
2011-01-31 01:20:00
2011-02-13 09:40:00
2011-02-26 18:00:00
2011-03-12 02:20:00

results matching ""

    No results matching ""