python快速学习5

输出

repr和str

str()和repr()都是将参数转化为字符串

如果参数本身为字符串,两种用法会有区别

>>> t = 'hallo,world'
>>> t
'hallo,world'
>>> str(t)
'hallo,world'
>>> repr(t)
"'hallo,world'"

如果参数为浮点数,保留的位数会有区别

>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'

对于其他情况,两种用法得到结果相同

>>> str(23)
'23'
>>> repr(23)
'23'

字符串格式函数

rjust(width)
右对齐,width为字符快递,超过宽度则能对齐多少多起多少

>>> for x in range(5,12):
...     print str(x).rjust(2)
...     
 5
 6
 7
 8
 9
10
11
>>> for x in range(5,12):
...     print str(x).rjust(1)
...     
5
6
7
8
9
10 #超过了宽度,能对齐一位就对齐一位,
11
>>> for x in range(1,200,30):
...     print str(x).rjust(2)
...     
 1
31
61
91
121
151
181

类似用法还有rjust(width)
format()

#基本用法
>>> print 'someone call me {} but others call me {}!'.format('song','lige')
someone call me song but others call me lige!
>>> print 'someone call me {0} but others call me {1}!'.format('song','lige')
someone call me song but others call me lige!
>>> print 'someone call me {1} but others call me {0}!'.format('song','lige')
someone call me lige but others call me song!
>>> print 'someone call me {realname} but others call me {virtname}!'.format(realname = 'song',virtname ='lige')
someone call me song but others call me lige!
>>> import math
>>> print 'the value of PI is {}'.format(math.pi)
the value of PI is 3.14159265359
>>> print 'the value of PI is {:.4f}'.format(math.pi)
the value of PI is 3.1416
# 与字典参数结合
>>> for name, grade in grade.items():
...     print '{0:10}  --->  {1:10d}'.format(name, grade)
...     
wu          --->          92
leng        --->          99
song        --->          88

%
也可以用%来格式化字符串

>>> print 'value of PI is %d' % math.pi
value of PI is 3
>>> print 'value of PI is %.3f' % math.pi
value of PI is 3.142

文件读写

open函数

#用法和C语言类似
>>> f = open('E:\test_for_filefun.txt','rb+')
>>> f.write('this is a test
')
>>> f.close()
>>> f = open('E:\test_for_filefun.txt','rb+')
>>> f.read()
'this is a test
'
>>> f.readline()
'' #读不到东西的时候返回''空字符串

相关的函数

  • f.tell()
    返回文件指针到文件开头的比特数目
  • f.seek(offset, from_what)
    from_what参数0,表示自文件开头开始,1表示从当前文件指针的位置开始,2表示从文件末尾开始
>>> f = open('E:\test_for_filefun.txt','rb+')
>>> f.readline()
"['192.168.1.1', '192.168.1.2', '192.168.1.176']
"
>>> f.tell()
48L
>>> f.seek(40)
>>> f.read(8)
"1.176']
"

小技巧

利用with参数处理文件
文件用完了之后会自动关闭

>>> with open('E:\test_for_filefun.txt','rb+') as f:
...     print f.readline()
...     
['192.168.1.1', '192.168.1.2', '192.168.1.176']

>>> f.closed   #f.closed可以用来判断文件是否关闭
True   #发现with语句执行完了之后文件的确关闭了

pickle模块

由于不同数据类型和字符串之间的转换很麻烦
所以引入了pickle模块:封装和解封
pickle.dump(x,fp)是将文件对象f封装到x中,然后x就是一个字符串,可以用来传递写入等操作
x = pickle.load(fp)从f中读取一个字符串,并且将它重构为python对象

原文地址:https://www.cnblogs.com/sslblog/p/6930416.html