python-格式化字符串

1.如何输出浮点型数据:  只需输入的是浮点型即可

1 >>> print 5-3
2 2
3 >>> print 5.0-3.0
4 2.0

 2.space_in_a_car中的“_”在代码中被假象为空格,用来隔开单词。在变量的命名中,最好能够通过变量的名字一目了然变量的意义,也样方便日后看代码或是别人看代码理解代码。

3.如果使用了非ASCII码编码(如注释中有汉字),需要在文件的第一行加一行代码,如下: 

 #--coding:utf-8--#

4.格式化字符串:

 

 输出结果为:

I have 100 cars
My name is lily
I have 100 cars
My naem is lily.
My name is lily, I have 100 car,I am so mZappy

%r,%s的区别:

%r 意思是“不管什么都打印出来”

%s 只打印字符串

 1 >>> print "this is a %s"%'apple'
 2 this is a apple
 3 >>> print "this is a %r"%'apple'
 4 this is a 'apple'
 5 >>> print "this is a %r"%'[apple]'
 6 this is a '[apple]'
 7 >>> print "this is a %r"%'%apple%'
 8 this is a '%apple%'
 9 >>> print "this is a %r"%('%apple%')
10 this is a '%apple%'
11 >>> print "this is a %r"%('(%apple%)')
12 this is a '(%apple%)'

 

1 >>> x = "this have %d people"%2
2 >>> print "I said: %r"%x
3 I said: 'this have 2 people'
4 >>> print "I said: %r"%("this have %d people"%2)
5 I said: 'this have 2 people'
6 >>> print "I said: %r"%"this have %d people"%2
7 I said: 'this have 2 people'

 

在输出的格式化字符中含有相乘,需要加括号“()”,否则会出错

>>> my_height = 74.0
>>> one_in = 2.54
>>> print"%d"%(my_height*one_in)
187
>>> print"%d"%my_height*one_in
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

 

格式化字符串符号的总结:http://blog.csdn.net/sding/article/details/4712651

posted on 2016-12-11 21:52  zhuzhu2016  阅读(177)  评论(0编辑  收藏  举报

导航