欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Python格式化输出

今天写程序又记不清格式化输出细节了……= =索性整理一下。

python print格式化输出。

1. 打印字符串

print ("His name is %s"%("Aviad"))

效果:

2.打印整数

print ("He is %d years old"%(25))

效果:

3.打印浮点数

print ("His height is %f m"%(1.83))

效果:

4.打印浮点数(指定保留小数点位数)

print ("His height is %.2f m"%(1.83))

效果:

5.指定占位符宽度

print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))

效果:

6.指定占位符宽度(左对齐)

print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))

效果:

7.指定占位符(只能用0当占位符?)

print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))

效果:

8.科学计数法

format(0.0015,'.2e')

效果:

 
分类: 编程
4
0
 
 
 
« 上一篇:吐槽win8
» 下一篇:dinner vs supper
posted @ 2014-05-28 17:28 MindProbe 阅读(92089) 评论(7编辑 收藏
 
 
  
#1楼 2014-07-15 18:35 suzhou  
你的皮肤不错,我很喜欢,可以分享一下吗?
  
#2楼[楼主2014-07-16 12:36 MindProbe  
@ suzhou
不清楚怎么分享皮肤……
我的皮肤是基于已有皮肤Dark改的。
皮肤,选择Dark,然后在自定义css中添加如下即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
body{
background-color#2b3036;
background-imageurl(null);
width:1200px;
margin:auto;
font-size:14px;
}
.posttitle a:hover {
color#f2eada;
font-size16px;
text-decorationnone;
}
div.posttitle {
font-size16px;
color#d6e9fc;
}
.posttitle a:active, .posttitle a:link {
color#d6e9fc;
font-size16px;
text-decorationnone;
}
p {
margin10px auto 10px auto;
text-indent0px;
font-size14px;
color#d3d7d4;
line-height200%;
}
a:hover {
text-decorationnone;
}
#header a {
color#87ceeb;
font-family'Corben', Georgia, Times, serif;
font-size30px;
font-weightbold;
}
.sub {
color#add8e6;
font-size14.7px;
margin-top15px;
}
h1.block_title {
color#d6e9fc;
font-size16px;
}
h1.block_title a:visited, h1.block_title a:active, h1.block_title a:link {
color#d6e9fc;
font-size16px;
}
  
#3楼 2015-05-31 20:48 老有才  
请问一下,我试了你上面的模板 CSS 代码,但是好像得到的不是你这个效果,是否你的 CSS 代码后来又作了更改?
  
#4楼 2016-05-31 20:26 jihite  
言简意赅
  
#5楼 2016-08-12 10:43 兮兮0703  
第五个指定占位符那个输入print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83)),我的错误,提示是TypeError: not all arguments converted during string formatting
  
#6楼 2016-12-02 10:49 starnight_cyber  
@ 兮兮0703
你可能在输入格式化字符串的时候,少输入了一个'%',导致出现这样的错误!
  
#7楼 2016-12-02 10:52 starnight_cyber  
博主,支持转载否?

来自  http://www.cnblogs.com/plwang1990/p/3757549.html



 

Python 3 语法小记(一)入门 (print 函数用法总结)

标签: pythonprint
 76828人阅读 评论(5) 收藏 举报
 分类:
[python] view plain copy
 
 print?
  1.   

写了一年C++后来自学Python,真是不太习惯,总感觉有点别扭,还是写博客记记语法,不然一下子就忘了,新手一个,只能一边学一边写,然后四处找找资料o(╯□╰)o

 

 

 

在 Python 3 中接触的第一个很大的差异就是缩进是作为语法的一部分,这和C++等其他语言确实很不一样,所以要小心咯

 

 

缩进要使用4个空格(这不是必须的,但你最好这么做),缩进表示一个代码块的开始,非缩进表示一个代码的结束。没有明确的大括号、中括号、或者关键字。这意味着空白很重要,而且必须要是一致的。第一个没有缩进的行标记了代码块,意思是指函数,if 语句、 for 循环、 while 循环等等的结束。

 

 

不过这样的规定也使得 Python 程序写出来会更加美观,便于阅读,吐槽是没有用的,接受吧...o(╯□╰)o

 

 

 

 

 

Python 思想:

“一切都是对象!”

 

 

 

输入很简单

 

  1. x = input("Please input x:")  
  2. Please input x:  

在代码最后加上

 

[python] view plain copy
 
 print?
  1. input("Press Enter")  

就可以让程序运行完后停一下

 

 

输出的 print 函数总结:

1. 字符串和数值类型
可以直接输出

 

[python] view plain copy
 
 print?
  1. >>> print(1)  
  2. 1  
  3. >>> print("Hello World")  
  4. Hello World  

2.变量
无论什么类型,数值,布尔,列表,字典...都可以直接输出

 

 

[python] view plain copy
 
 print?
  1. >>> x = 12  
  2. >>> print(x)  
  3. 12  
  4. >>> s = 'Hello'  
  5. >>> print(s)  
  6. Hello  
  7. >>> L = [1,2,'a']  
  8. >>> print(L)  
  9. [12'a']  
  10. >>> t = (1,2,'a')  
  11. >>> print(t)  
  12. (12'a')  
  13. >>> d = {'a':1'b':2}  
  14. >>> print(d)  
  15. {'a'1'b'2}  

3.格式化输出
类似于C中的 printf

 

 

[python] view plain copy
 
 print?
  1. >>> s  
  2. 'Hello'  
  3. >>> x = len(s)  
  4. >>> print("The length of %s is %d" % (s,x))  
  5. The length of Hello is 5  

看看《Python基础编程》中对格式化输出的总结:

 

(1). %字符:标记转换说明符的开始


(2). 转换标志:-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充


(3). 最小字段宽度:转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出。


(4). 点(.)后跟精度值:如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将从元组中读出

 

(5).字符串格式化转换类型


转换类型          含义

d,i                 带符号的十进制整数
o                   不带符号的八进制
u                   不带符号的十进制
x                    不带符号的十六进制(小写)
X                   不带符号的十六进制(大写)
e                   科学计数法表示的浮点数(小写)
E                   科学计数法表示的浮点数(大写)
f,F                 十进制浮点数
g                   如果指数大于-4或者小于精度值则和e相同,其他情况和f相同
G                  如果指数大于-4或者小于精度值则和E相同,其他情况和F相同
C                  单字符(接受整数或者单字符字符串)
r                    字符串(使用repr转换任意python对象)
s                   字符串(使用str转换任意python对象)

 

[python] view plain copy
 
 print?
  1. >>> pi = 3.141592653  
  2. >>> print('%10.3f' % pi) #字段宽10,精度3  
  3.      3.142  
  4. >>> print("pi = %.*f" % (3,pi)) #用*从后面的元组中读取字段宽度或精度  
  5. pi = 3.142  
  6. >>> print('%010.3f' % pi) #用0填充空白  
  7. 000003.142  
  8. >>> print('%-10.3f' % pi) #左对齐  
  9. 3.142       
  10. >>> print('%+f' % pi) #显示正负号  
  11. +3.141593  

4.如何让 print 不换行
在Python中总是默认换行的

 

 

[python] view plain copy
 
 print?
  1. >>> for x in range(0,10):  
  2.     print(x)  
  3.   
  4.       
  5. 0  
  6. 1  
  7. 2  
  8. 3  
  9. 4  
  10. 5  
  11. 6  
  12. 7  
  13. 8  
  14. 9  

如果想要不换行,之前的 2.x 版本可以这样 print x, 在末尾加上 ,
但在 3.x 中这样不起任何作用
要想换行你应该写成 print(x,end = '' )

 

 

[python] view plain copy
 
 print?
  1. >>> for x in range(0,10):  
  2.     print (x,end = '')  
  3.   
  4.       
  5. 0123456789  


 

 

拼接字符串:

 

[python] view plain copy
 
 print?
  1. >>> "Hello""World"  
  2. 'HelloWorld'  
  3. >>> x = "Hello"  
  4. >>> y = "world"  
  5. >>> xy  
  6. Traceback (most recent call last):  
  7.   File "<pyshell#10>", line 1in <module>  
  8.     xy  
  9. NameError: name 'xy' is not defined  
  10. >>> x+y  
  11. 'Helloworld'  

 

 

pow函数:

[python] view plain copy
 
 print?
  1. # 2**3%5(2的3次幂对5取模)  
  2. >>> pow(2,3,5)  
  3. 3  

然后很重要一点是类型可以自由地转换,你赋什么值,变量就是什么类型,python会自动帮你管理

这点真让我的C++思维转不过来呢

 

  1. >>> x = 2  
  2. >>> type(x)  
  3. <class 'int'>  
  4. >>> x = 2.3  
  5. >>> type(x)  
  6. <class 'float'>  
  7. >>> x = [2,3]  
  8. >>> type(x)  
  9. <class 'list'>  

部分函数:

 

abs(number),返回数字的绝对值

cmath.sqrt(number),返回平方根,也可以应用于负数

float(object),把字符串和数字转换为浮点数

help(),提供交互式帮助

input(prompt),获取用户输入

int(object),把字符串和数字转换为整数

math.ceil(number),返回数的上入整数,返回值的类型为浮点数

math.floor(number),返回数的下舍整数,返回值的类型为浮点数

math.sqrt(number),返回平方根不适用于负数

pow(x,y[.z]),返回X的y次幂(有z则对z取模)

repr(object),返回值的字符串标示形式

round(number[.ndigits]),根据给定的精度对数字进行四舍五入

str(object),把值转换为字符串

来自 http://blog.csdn.net/jcjc918/article/details/9354815

跟老齐学Python之print详解

投稿:hebedich 字体:[增加 减小] 类型:转载 时间:2014-09-28 我要评论

print的一些基本用法,在前面的讲述中也涉及一些,本讲是在复习的基础上,尽量再多点内容。

eval()

在print干事情之前,先看看这个东东。不是没有用,因为说不定某些时候要用到。

 

复制代码代码如下:

>>> help(eval)      #这个是一招鲜,凡是不理解怎么用,就用这个看文档

 

Help on built-in function eval in module __builtin__:

eval(...)
    eval(source[, globals[, locals]]) -> value

    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

 

能看懂更好了,看不懂也没有关系。看我写的吧。哈哈。概括一下,eval()是把字符串中符合python表达式的东西计算出来。意思就是:

 

复制代码代码如下:

>>> 3+4         #这是一个表达式,python会根据计算法则计算出结果来
7
>>> "3+4"       #这是一个字符串,python就不计算里面的内容了,虽然里面是一个符合python规范的表达式
'3+4'
>>> eval("3+4") #这里就跟上面不一样了,就把字符串里面的表达式计算出来了
7

 

下面再看一个字符串“相加”的例子:

 

复制代码代码如下:

>>> "qiwsir"+".github.io"
'qiwsir.github.io'
>>> "'qiwsir'+'.github.io'"    #字符串里面,python是不会进行“计算”的
"'qiwsir'+'.github.io'"
>>> eval("'qiwsir'+'.github.io'") #eval()做的事情完全不一样,它会把字符串里面的计算出来
'qiwsir.github.io'

 

顺便再说一下另外一个跟eval()有点类似的函数:exec(),这个函数专门来执行字符串或文件里面的python语句。

 

复制代码代码如下:

>>> exec "print 'hello, qiwsir'"
hello, qiwsir
>>> "print 'hello, qiwsir'"
"print 'hello, qiwsir'"

 

print详解

print命令在编程实践中用的比较多,特别是要向看看程序运行到某个时候产生了什么结果了,必须用print来输出,或者说,本讲更宽泛地说,就要说明白把程序中得到的结果输出问题。

比较简单的输出,前面已经涉及到过了:

 

复制代码代码如下:

>>> name = 'qiwsir'
>>> room = 703
>>> website = 'qiwsir.github.io'
>>> print "MY name is:%s\nMy room is:%d\nMy website is:%s"%(name,room,website)
MY name is:qiwsir
My room is:703
My website is:qiwsir.github.io

 

其中,%s,%d就是占位符。

 

复制代码代码如下:

>>> a = 3.1415926
>>> print "%d"%a    #%d只能输出整数,int类型
3
>>> print "%f"%a  #%f输出浮点数
3.141593
>>> print "%.2f"%a #按照要求输出小数位数
3.14
>>> print "%.9f"%a  #如果要求的小数位数过多,后面就用0补全
3.141592600
>>> b = 3          
>>> print "%4d"%b   #如果是整数,这样写要求该整数占有四个位置,于是在前面增加三个空格
   3                #而不是写成0003的样式

 

换一种范式,写成这样,就跟上面有点区别了。

 

复制代码代码如下:

>>> import math     #引入数学模块
>>> print "PI=%f"%math.pi #默认,将圆周率打印成这个样子
PI=3.141593
>>> print "PI=%10.3f"%math.pi #约束一下,这个的含义是整数部分加上小数点和小数部分共计10位,并且右对齐
PI=     3.142
>>> print "PI=%-10.3f"%math.pi #要求显示的左对齐,其余跟上面一样
PI=3.142
>>> print "PI=%06d"%int(math.pi) #整数部分的显示,要求共6位,这样前面用0补足了。
PI=000003

 

其实,跟对上面数字操作类似,对字符串也可以做一些约束输出操作。看下面实验,最好看官也试试。

 

复制代码代码如下:

>>> website
'qiwsir.github.io'
>>> print "%.3s"%website
qiw
>>> print "%.*s"%(3,website)
qiw
>>> print "%7.3s"%website
    qiw
>>> print "%-7.3s"%website
qiw    

 

总体上,跟对数字的输出操作类似。不过,在实际的操作中,这些用的真的不是很多,至少在我这么多年的代码生涯中,用到上面复杂操作的,就是现在给列位展示的时候,充其量用一用对float类型的数据输出小数位数的操作,其它的输出操作,以默认的那种方式居多。请看官在这里鄙夷我的无知吧。

行文到此,提醒列位,如果用python3的,请用print(),要加个括号。

print有一个特点,就是输出的时候,每行后面都自动加上一个换行符号\n,这个在前面已经有所提及。

 

复制代码代码如下:

>>>  website
'qiwsir.github.io'
>>> for word in website.split("."):
...     print word
... 
qiwsir
github
io
>>> for word in website.split("."):
...     print word,         #注意,加了一个逗号,输出形式就变化了吧。
... 
qiwsir github io

 

%r是万能的吗?

我曾经说过,懒人改变世界,特别是在敲代码的领域。于是就有人问了,前面一会儿是%s,一会儿是%d,麻烦,有没有一个万能的?于是网上就有人给出答案了,%r就是万能的。看实验:

 

复制代码代码如下:

>>> import math
>>> print "PI=%r"%math.pi
PI=3.141592653589793
>>> print "Pi=%r"%int(math.pi)
Pi=3

 

真的是万能呀!别着急,看看这个,你是不是就糊涂了?

 

复制代码代码如下:

>>> print "Pi=%s"%int(math.pi)
Pi=3

 

当然,这样就肯定出错了:

 

复制代码代码如下:

>>> print "p=%d"%"pi"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

 

如果看到这里,看官有点糊涂是很正常的,特别是那个号称万能的%r和%s,怎么都能够对原本属于%d的进行正常输出呢?

其实,不管是%r还是%s(%d)都是把做为整数的对象转化为字符串输出了,而不是输出整数。但是%r和%s是有点区别的,本讲对这个暂不做深入研究,只是说明这样的对应:%s-->str();%r-->repr(),什么意思呢?就是说%s调用的是str()函数把对象转化为str类型,而%r是调用了repr()将对象转化为字符串。关于两者的区别请参考:Difference between str and repr in Python,下面是一个简单的例子,演示一下两者区别:

 

复制代码代码如下:

>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2014, 8, 15)
>>> str(today)
'2014-08-15'
>>> repr(today)
'datetime.date(2014, 8, 15)'

 

最后要表达我的一个观点,没有什么万能的,一切都是根据实际需要而定。

关于更多的输出格式占位符的说明,这个页面中有一个表格,可惜没有找到中文的,如果看官找到中文的,请共享一下呀:string formatting

再扩展

 

复制代码代码如下:

>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> print "qiwsir is in %(room)d"%myinfo
qiwsir is in 703

 

看官是否看明白上面的输出了?有点意思。这样的输出算是对前面输出的扩展了。

出了这个扩展之外,在输出的时候,还可以用一个名曰:format的东西,这里面看不到%,但是多了{}。看实验先:

 

复制代码代码如下:

>>> print "My name is {0} and I am in {1}".format("qiwsir",703)     #将format后面的内容以此填充
My name is qiwsir and I am in 703
>>> "My website is {website}".format(website="qiwsir.github.io")    #{}里面那个相当于一个变量了吧
'My website is qiwsir.github.io'

 

看到这里,是不是感觉这个format有点意思?一点不输给前面的输出方式。据说,format会逐渐逐渐取代前面的。关于format,我计划后面一讲继续。这里只是来一个引子,后面把用format输出搞得多点。

来自  http://www.jb51.net/article/55768.htm


普通分类: