Python学习笔记-小记

1.字符串string

推断一个字符(char)是数字还是字母

str.isalpha() #推断是否为字母
str.isdigit() #推断是否为数字

推断一个字符串是否为空

if not str.strip(): #推断是否为空,true表示空

向字符串加入内容

str = ''.join('love')

得到字符串固定长度的字串

>>>str = str1[1:3] #得到从下标1開始到下标3之前的字符,下标3的字符不算

字符串替换

>>>str.replace('abc','cde')

2.列表list

推断一个列表是否为空

>>>if len(lists):   #true表示空
#向列表中加入数据
>>>lists.append('1')
#得到list某个值的下标
>>>lists.index('1')

3.文件操作

读文件

>>>with open('filename','r') as f1:

写文件

>>>with open('filename','w') as f2:
>>> ......
>>> f2.write('my name is ldw.')

获得整个文件夹文件

>>>import os
>>>files = os.listdir("/ifs/home/liudiwei")
>>>for onefile in files:    #onefile即递归得到的每一个文件
>>> ...               

推断当前文件夹是否存在,不存在则创建文件夹:

if not os.path.exists(outdir): #假设outdir不存在,则创建该文件夹
        os.makedirs(outdir)

python运行当前系统命令

os.system('[command]')  #command为想要运行的命令

4.集合操作

创建集合

s = set('thisisset')

加入元素

s.add('z')

集合长度

len(s)

推断集合非空

if len(s):   #假设长度为0,返回false

推断集合存在某元素

'k' in s    #或者能够是 'k' not in s

回收元素

del s

5.浮点数除法

设a和b为两整数。两数相除须要得到浮点结果

c=float(a)/float(b)

如须要保留小数

c=float('%.3f' % float(a)/float(b))

6.构建数组

生成一个8000*4的数组矩阵

def genMatrix(): 
    AA=['A','C','D','E','F',
        'G','H','I','K','L',
        'M','N','P','Q','R',
        'S','T','V','W','Y',]
    triplet = []
    for i in range(len(AA)):
        for j in range(len(AA)):
            for k in range(len(AA)):
                triplet.append(AA[i]+AA[j]+AA[k])

    rna=['A','U','G','C']
    matrix = [[0 for col in range(len(rna))] for row in range(len(triplet))]  
    return triplet,rna,matrix' 

7.字典

python字典比較有用,跟java/c++中的map相似。键值对。在实际其中,python能够依据键找到value。
定义

dict_map = {}
#赋值
dict_map['number'] = 2
#查看是否存在某个键
dict_map.has_key('number')#if exist, return True,else return False
原文地址:https://www.cnblogs.com/cxchanpin/p/7073947.html