python 常用方法集锦

一,字符串截取

print str[0:3] #截取第一位到第三位的字符

print str[-3:] #截取倒数第三位到结尾

print str[:5] #截取千5个字符

二、文件读写

fpfile = open(file_name)

for line in fpfile.readlines():

line = line.strip()

    read(size) 不加SIZE可以是整个文件读取,加上SIZE可以一部分一部分的读取,对于大文件要使用SIZE分段读取,对于小文件可以整体读取
    readline() 一次读取一行
    readlines() 一次读取全部文件到一个列表,适合读取配置文件,因为配置文件通常都是一行一行的,对于配置文件这种非常适合因为它比较小而且

三、utf8汉字问题

import sys

reload(sys)

sys.setdefaultencoding( “utf-8” )

四、运行参数帮助文档换行

引入textwrap, 在ArgumentParser初始化时用  formatter_class=argparse.RawTextHelpFormatter

import argparse, textwrap

parser = argparse.ArgumentParser(description=‘some information’, usage=‘use “python %(prog)s –help” for more information’, formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument(‘–argument’, default=somedefault, type=sometype, help= textwrap.dedent(‘\ First line Second line More lines ))

You May Also Like

About the Author: daidai5771

发表评论

电子邮件地址不会被公开。 必填项已用*标注