Python基本运算符
基本数据类型有
数字
字符串
列表
元组
字典
集合
反斜杠的作用:
The backslash () character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
一 字符串
字符串最基本的玩法:
https://docs.python.org/3/tutorial/introduction.html#strings
优先掌握的操作
1. strip, lstrip
2. lower, upper
3. startswith, endswith
4. format的三种玩法
5. split, rsplit
6. join
7. replace
8. isdisgit
#strip
name='*parker**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*'))
#lower&upper
name = 'parker'
print(name.lower())
print(name.upper())
#format的三种玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18)
#split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到顶级目录
print(name.split('/',1))
name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分
#join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串
#replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1))
#isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit())
二 集合
官网介绍:https://docs.python.org/3/tutorial/datastructures.html#sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
代码
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
三、列表
#定义:[]内可以有多个任意类型的值,逗号分隔
my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...])
或
l=list('abc')
#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in
#5、追加
#6、删除
#7、循环
用法
#ps:反向步长
l=[1,2,3,4,5,6]
#正向步长
l[0:3:1] #[1, 2, 3]
#反向步长
l[2::-1] #[3, 2, 1]
#列表翻转
l[::-1] #[6, 5, 4, 3, 2, 1]
四、元组
#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读
#定义:与列表类型比,只不过[]换成()
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))
#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in
#5、循环
五、字典
#作用:存多个值,key-value存取,取值速度快
#定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)
#优先掌握的操作:
#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in
#4、删除
#5、键keys(),值values(),键值对items()
#6、循环
数据类型总结:
按存储空间的占用部分(从低到高)
数字
字符串
集合:无序,即无序存索引相关信息
元组:有序,需要存索引相关信息,不可变
列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改
运算符
#身份运算(is ,is not)
is比较的是id,而双等号比较的是值
毫无疑问,id若相同则值肯定相同,而值相同id则不一定相同
>>> x=1234567890
>>> y=1234567890
>>> x == y
True
>>> id(x),id(y)
(3581040, 31550448)
>>> x is y
False
python 常见问题
Python字符串处理的应用:
检验一个IP地址是否是合法字符串,若是则返回True,否则返回FALSE:
def scan(one_string):
if '.' not in one_string:
return False
elif one_string.count('.') != 3:
return False
else:
flag = True
one_list = one_string.strip().split('.')
for i in one_list:
try:
one_num = int(i)
if one_num >= 0 and one_num <= 255:
pass
else:
flag = False
except:
flag = False
return flag
Python 统计文章的单词数目
def getText():
text = open('article.txt').read().lower()
for mark in '!@#$%^&*(){}[]?/<>':
text.replace(mark,'')
return text
myContent = getText().split()
counts = {}
for word in myContent:
counts[word] = counts.get(word,0)+1
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word,count = items[i]
print('{0:<10}:{1:>5}'.format(word,count))