17、如何对字符串进行左, 右, 居中对齐 18、如何去掉字符串中不需要的字符 19、如何读写文本文件 20、如何处理二进制文件 21、如何设置文件的缓冲

17、如何对字符串进行左, 右, 居中对齐

info = "GBK"
print(info.ljust(20))
print(info.ljust(20,'#'))
print(info.rjust(20,'#'))
print(info.center(20,"#"))
print(format(info,'<20'))
print(format(info,'>20'))
print(format(info,'^20'))


result:
GBK                 
GBK#################
#################GBK
########GBK#########
GBK                 
                 GBK
        GBK         

18、如何去掉字符串中不需要的字符

 

PS:方法四 在py3里已经不支持删除多种字符串了,只保留给字符串重新映射

#strip删除两边,lstrip删除左边,rstrip删除右边,只能删除两端的
info = "      GBK      "
print(info.strip(),info.lstrip(),info.rstrip())
info2 = "+++GBK---"
print(info.strip('+-'))
#删除::str切片+拼接
info3 = "abc::def"
print(info3[:3]+info3[5:])

#replace方法可以替换str中间的字符,一次只能替换一种
info4 = "afsd$asdf$asdf^asdf"
print(info4.replace('$',''))

#使用re.sub可以一次替换多种
import re
print(re.sub('[$^]','',info4))
#使用translate替换,translate有个功能,可以给str加入映射表,达到进行加密的目的
print(str.maketrans('abcxyz','xyzabc'))
info5 = 'abcxy	z
6
66gggxyz'
print(info5.translate(str.maketrans('abcxyz','xyzabc')))

结果:
GBK GBK             GBK
      GBK      
abcdef
afsdasdfasdf^asdf
afsdasdfasdfasdf
{97: 120, 98: 121, 99: 122, 120: 97, 121: 98, 122: 99}
6
66gggabc

19、如何读写文本文件

python2中,默认编码是unicode编码,这种编码不能直接存储物理硬件(磁盘的扇区、网络的socket)中,需要转换成string(由连续的字节组成)

info = u'你好'
print(info)
print(info.encode('utf-8'))

result:

你好
b'xe4xbdxa0xe5xa5xbd'

在py2中,如果没有编码成str,数据不能写进文件中

info = u'你好'
with open('H3','w') as f:
    #存入文件前,需要先编码成str
    f.write(info)

retsult:
Traceback (most recent call last):
  File "C:/laoni/PycharmProjects/Pythontest/test2.py", line 46, in <module>
    f.write(info)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)


读取文件也需要解码:
with open('H3','r') as f2:
t = f2.read()
print(t.decode('utf8'))
 

在py3中 py2的str变成了byte,unicode变成了str(真正意义上的连续字符串),在py3 表示byte需要在字符串前加个b

在py2中需要加个u''表示unicode字符串,而py3中默认就是unicode(也就是str),不需要添加。

在py3中open函数功能更强大,可以使用encoding指定编码格式

info = '你好'
#open通过encoding参数自动编码成utf8
with open('H3','wt',encoding='utf8') as f:
    f.write(info)

#读取文件的时候,自动解码成utf8,不要和上面存入时的编码搞混,文件里的数据显示的是连续的字节
with open('H3','rt',encoding='utf8') as f2:
    print(f2.read())

20、如何处理二进制文件

 

 

 21、如何设置文件的缓冲

#全缓冲
f = open("demo.txt",'w',buffering=2000)
f.write('+' *2001)

#行缓冲
f2 =open("demo.txt",'w',buffering=1)

#无缓冲
f3 = open("demo.txt",'w',buffering=0)
原文地址:https://www.cnblogs.com/laonicc/p/6753915.html