strip()
方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
str.strip([chars]);
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
split()
通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
str.split(str="", num=string.count(str)).
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
以上输出:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
open()
open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数。
注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file: 必需,文件路径(相对或者绝对路径)。
mode: 可选,文件打开模式
buffering: 设置缓冲
encoding: 一般使用utf8
errors: 报错级别
newline: 区分换行符
closefd: 传入的file参数类型
opener:
file 对象使用 open 函数来创建,比如: file = open('params.txt','r')
下表列出了 file 对象常用的函数: