python数据类型及其操作

一、数字

常用类型:int,float

age = 10  # int型

salary = 3000.5  # float型

进制:

二进制:

11 = 1*21 + 1*20 = 3

八进制:

11 = 1*81 + 1*80 = 9

十进制:

11 = 1*101 + 1*100 = 11

十六进制:

11 = 1*161 + 1*160 = 17

进制转换:

十进制转为二进制:

age = 10

print(bin(age)) => 0b1010

二进制转为十进制:

1010 = 1*23 + 0*22 + 1*21 + 0*20 = 10

十进制转为八进制:

print(oct(age)) => 0o12

十进制转为十六进制:

print(hex(age)) => 0xa

二、字符串

创建字符串:

>>> name = 'johnny'   # name = str('johnny')
>>> print(type(name))
str
>>> print(name[0])
j

基本操作:

移除空白

>>> name = input('username:')
>>> print(name)
username:      johnny        
      johnny   
>>> name = name.strip()
>>> print(name)
username: johnny
johnny

>>> name = input('username').strip()
>>> print(name)

>>> name = '***johnny*****'
>>> print(name.strip('*'))
johnny
>>> print(name.lstrip('*'))
johnny*****
>>> print(name.rstrip('*'))
***johnny

切分

>>> user_info = 'root:x:0:0::/root:/bin/bash'
>>> print(user_info.split(':'))
['root','x','0','0','','/root','/bin/bash']
>>> print(user_info.split(':')[5])
/root
>>> msg = 'name johnny age 10'
>>> print(msg.split())
['name','johnny','age','10']

统计长度

>>> name = 'johnny'
>>> print(len(name))  #相当于 name.__len__()
6

切片

>>> name = 'hello world'
>>> print(name[1:3])
el
>>> print(name[1])
e
>>> print(name[1:9:2])
el o

其它操作

#startswith,endwith
>>> name = 'johhny_dd'
>>> print(name.endswith('dd'))
True
>>> print(name.startswith('j'))
True

#replace
>>> name = ' Today is a good day,choose you like'
>>> print(name.replace('Today','Tomorrow'))
Tomorrow is a good day,choose you like

#format
>>> print('{} {} {}'.format('johnny',18,'male'))
johnny 18 male
>>> print('{0} {1} {0}'.format('johnny',18,'male'))
johnny 18 johnny
>>> print('{name} {age} {sex}'.format(name='johnny',age=18,sex='male'))
johnny 18 male
>>> print('NAME:{name} AGE:{age} SEX:{sex}'.format(name='johnny',age=18,sex='male'))
NAME:johnny AGE:
18 SEX:male #isdigit >>> num = '123' >>> print(num.isdigit()) True who_age = 10 whileTrue: age = input('>>:').strip() if len(age) == 0:continue if age.isdigit(): age = int(age) print(age,type(age))
#find,index,count >>> name = 'johnny' >>> print(name.find('o')) 1 >>> print(name.find('x')) -1 >>> print(name.index('o')) 1 >>> print(name.find('x')) 报错 >>> name = 'johnny hello' >>> print(name.find('o',2,4)) -1 >>> print(name.count('o')) 2 >>> print(name.count('o',0,3)) 1 #join 都必须是字符串 >>> l = ['johnny','say','hello','world'] >>> print(':'.join(l)) johnny:say:hello:world >>> l1 = ['johnny',11] >>> print(';',join(l1)) 报错
#center,ljust,rjust,zfill >>> name = 'johnny' >>> print(name.center(30,'*')) ************johnny************ >>> print(name.ljust(30,'*')) johnny************************ >>> print(name.rjust(30,'*')) ************************johnny >>> print(name.zfill(30)) 000000000000000johnny #lower,upper >>> name = 'JOHNNY' >>> print(name.lower()) johnny >>> name = 'johnny' >>> print(name.upper()) JOHNNY #capitalize,title >>> msg = 'johnny say ji' >>> print(msg.capitalize()) Johnny say hi >>> print(msg.title) >>> Johnny Say Hi #isalnum,isalpha >>> name = 'johnny123' >>> print(name.isalnum()) True >>> print(name.isalpha()) False

#in
>>> msg = 'my name is johnny'
>>> print('johnny' in msg)
>>> msg = 'hello'
>>> a,b,c,d,e = msg
>>> print(a,b,c,d,e)
h e l l o

三、列表

创建列表:

name = ['unknown','working','safe']

name = list(['unknown','working','safe'])

基本操作:

索引

>>> name = ['unknown','working','safe',4,6,1]
>>> print(name[1])
working

切片

>>> print(name[1:3])

['working','safe']

追加,一次只能追加一个值

>>> name.append('hobby')
>>> print(name)
['unknown','working','safe',4,6,1,'hobby']

插入

>>> name = ['ruwee','johnny','ruwee','nihao','hello','world']
>>> name.insert(2,'mo')
>>> print(name)
['ruwee','johnny','mo','ruwee','nihao','hello','world']

删除 pop

>>> name.pop()      #默认从后面删除,按照索引进行删除
['unknown','working','safe',4,6,1]
>>> name.pop(0)
['working','safe',4,6,1,'hobby']

删除 remove  按照值进行删除

>>> name.remove('working')

['safe',4,6,1,'hobby']

长度

>>> name = ['unknown','working','safe']
>>> print(len(name))
3

包含

>>> print('unknown' in name)
True

其它操作

>>> my_friends = ['ruwee','johnny','ruwee','nihao','hello','world']
>>> my_friends.clear()  #清空所有
>>> l = my_friends.copy()
>>> print(l)
['ruwee','johnny','ruwee','nihao','hello','world']
>>> print(my_friends.count('ruwee'))
2
>>> print(my_friends.extend(['how','are','you']))      #一次性添加多个值
['ruwee','johnny','ruwee','nihao','hello','world','how','are','you']
>>> print(my_friends.index('how'))
6
>>> print(my_friends.reverse())
['you','are','how','world','hello','nihao','ruwee','johnny','ruwee']
>>> l = [4,6,1,-1]
>>> l.sort()
>>> print(l)
[-1,1,4,6]
>>> data = ['johnny',22,[23,1,2]]
>>> name,age,birth = data
>>> print(name)
'johnny'
>>> print(age)
22
>>> print(birth)
[23,1,2]

四、字典

创建字典:

person = {'tom':12,'jerry':15,'peter':20}

person = dict({'tom':'12','jerry':'15','peter':'20'})

基本操作:

索引

>>> print(person['tom'])
12

新增

>>> person['height'] = 1.8
>>> print(person)
{'tom':12,'jerry':15,'peter':20,'height':1.8}
>>> dic = {'a':1,'b':2}
>>> person.update(dic)
>>> print(person)
{'tom':12,'jerry':15,'peter':20,'height':1.8,'a':1,'b':2}

删除

>>> person.pop('tom')
>>> print(person)
{'jerry':15,'peter':20,'height':1.8}
>>> print(person.pop('sdfdsff',None))
None

获取值

>>> person = {'tom':12,'jerry':15,'peter':20}
>>> print(person.get('tom'))
12
>>> print(person.get('sdf'))
None
>>> print(person['dsf'])
报错

键值对

>>> print(person.keys())
dict_keys(['tom','jerry','peter'])
>>> print(person.values())
dict_values([12,15,20])
>>> print(person.items())
dict_items([('tom',12),('jerry',15),('peter',20)])

>>> d={}
>>> d['name']='tom'
>>> d['age']=12
>>> d['sex']='male'
>>> d.setdefault('hobby',['basketball','football','pingpang'])
['basketball', 'football', 'pingpang']
>>> d
{'name': 'tom', 'age': 12, 'sex': 'male', 'hobby': ['basketball', 'football', 'pingpang']}

循环

for key,value in person.items():
    print(key,value)

五、集合

集合内可以有多个元素,但是每个元素都必须是不可变类型

集合内的元素唯一

集合是无序的

创建集合:

>>> s = {3,4,7,1}
或
>>>set__test = set('world')
>>>print(set_test)
{'w','d','l','o','r'}
>>> s1 = set('hello')
>>> print(s1)
{'o','e','l','h'}

基本操作:

in , not in

>>> pythons = {'hello','how','are','you','fine','thank'}
>>> print('hello' in pythons)
True

| 并集

>>> s1={1,10,11,22}
>>> s2 = {1,11,33}
>>> print(s1 | s2)
{1,33,10,11,22}

& 交集

>>> s1={1,10,11,22}
>>> s2 = {1,11,33}
>>> print(s1&s2)
{1,11}

- 差集

>>> s1={1,10,11,22}
>>> s2 = {1,11,33}
>>> print(s1 - s2)
{10,22}

^ 对称差集

>>> s1={1,10,11,22}
>>> s2 = {1,11,33}
>>> print(s1 ^ s2)
{33,22,10}

父集

>>> s1 = {1,2,3,4}
>>> s2 = {1,2}
>>> print(s1 >= s2)
True

子集

>>> print(s1 <= s2)
False

其它操作

>>> s = set([3,5,9,10])
>>> print(s.pop()) # 随机删值
>>> t = set('Hello') >>> t.add('x') >>> s.update([10,37,42]) >>> t.remove('H') # 删除不存在的会报错
>>> t.discard('dfsfsd') # 删除不存在的不会报错
>>> len(s)
>>> s=set() # 空集合
>>> y={} # 空字典

六、元组

元组不可变,主要用来读

创建元祖:

age = (32,12,54,25)

age = tuple((32,12,54,25))

基本操作:

索引

>>> age = (32,12,54,25)
>>> print(age[2])
54

切片

>>> print(age[0:3])
(32,12,54)

长度

>>> print(len(age))
4

包含

>>> print(12 in age)
True

 其它操作

>>> printt(age.index(25))
3
>>> print(age.count(32))
1

补充

>>>res=input('>>: ')
123             #字符串类型
>>>l=eval(res)          #把字符串中的命令拿出来执行一遍
>>>type(l)
<class 'list'>
>>>
>>>eval('print("ok")')
ok

八、文件处理

流程:

1.打开文件,得到句柄并且赋给一个变量

2.通过句柄进行文件操作

3.关闭文件

基本操作:

读取文件

f = open('a.txt','r',encoding='utf-8')
res = f.read()
print(res)
print(f.readline())
f.close()

with方式打开的文件在操作结束后可以自动关闭文件

with open('a.txt','r',encoding='utf-8') as f:
    pass

写入文件

f=open('a.txt','w',encoding='utf-8')
f.write('11111
')
f.writelines(['a
','b
','c
'])
f.close()

替换文本中的内容

#old.txt
alex hahaha
woca le alex
alex qunimeide

alex feile feile
import os
with open('old.txt','r',encoding='utf-8') as read_f,
    open('.old.txt.swap','w',encoding='utf-8') as write_f:
    for line in read_f:
        if 'SB' in line:
            line=line.replace('SB','alex')   # 目前改的还是内存级别的
        write_f.write(line)                # 刷回到硬盘
os.remove('old.txt')
os.rename('.old.txt.swap','old.txt')
原文地址:https://www.cnblogs.com/Ryans-World/p/7158537.html