在查找比较字符串的方法的时候碰到的,用该方法对之前写的代码进行了改进,使得输出的结果格式与文件中的格式完全一致了。上述改进用于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)