python 学习

在查找比较字符串的方法的时候碰到的,用该方法对之前写的代码进行了改进,使得输出的结果格式与文件中的格式完全一致了。上述改进用于read_C_func.py以及read_b.py。

http://book.51cto.com/art/201411/456725.htm

2、如何比较两个字符串,并且忽略大小写、空白字符、TAB 制表符、换行等。这个很容易解决,把字符串转换成小写后 split,然后以空格为分隔符 join 在一起。

#!/usr/bin/python

a = "  \t\n\n a    B C   d\t\n\n\n"
b = "\t\t\n\n a    b c   D\n\n\n\n"

s1 = a.lower()
s1 = ' '.join(s1.split())
s2 = b.lower()
s2 = ' '.join(s2.split())

if s1 == s1:
        print "=="
else:
        print "!="

 

3.写出到文件中的方法

方法一:(page 112)

out_1=open('out_1.txt',w)
 print(man,file=out_1)

out_1.close()

方法二:

f=open('out_1.txt',w)
f.write('a')

f.close()

4.try except finally 与 try except

try:
data = open('its.txt', "w")
print("It's...", file=data)
except IOError as err:
print('File error: ' + str(err))
finally:
if 'data' in locals():
data.close()

与下面代码等价

try:
with open('its.txt', "w") as data:
print("It's...", file=data)
except IOError as err:
print('File error: ' + str(err))

 

5.

with open('man_data.txt', 'w') as man_file, open('other_data.txt’, 'w’) as other_file:
print(man, file=man_file)
print(other, file=other_file)

与下面代码等价

with open(‘man_data.txt', ‘w') as man_file:
print(man, file=man_file)
with open(‘other_data.txt', ‘w') as other_file:
print(other, file=other_file)

6. dump and load  写读数据

import pickle
...
with open('mydata.pickle', 'wb') as mysavedata:#二进制方式
pickle.dump([1, 2, 'three'], mysavedata)
...
with open('mydata.pickle', 'rb') as myrestoredata:#二进制方式
a_list = pickle.load(myrestoredata)
print(a_list)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值