Python运维开发:03 字符串和字典
字符串
定义
使用单引号、双引号、三个单引号或三个双引号引起来的一些字符
特殊字符
- \ 转义符
- \r 回车
- \n 换行
- \t tab键
- \f 换页
访问与修改字符串
访问
- 字符串是有序的数据集,通过字符串名[索引]的方式访问字符串中的元素
- 索引编号
从左向右依次为0,1,2,3,…,n – 1
从右向左一次为-1,-2,-3,…,-n
- 访问元素的索引必须存在,否则报错
字符串不能修改
遍历字符串
- 使用for访问元组中所有的元素
- 类型转换
可以通过函数str将其他可遍历的类型转化为字符串
字符串常见操作
- 获取str元素的数量
- 获取str中元素最大值、最小值
- 判断元素是否在str中存储
字符串运算
四则运算
- 加(+) :必须为两个str相加
- 乘(*):必须一个为整数
字符串函数

- count 计算字符串中出现子字符串的次数
'abcbc'.count('c')
2
- index 计算字符串中出现子字符串位置,若不存在则报错
>>> 'abc'.index('b')
1
>>> 'abc'.index('bcd')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: substring not found
- find 计算字符串中出现子字符串位置,若不存在则返回-1
>>> 'abc'.find('b')
1
>>> 'abc'.find('bcd')
-1
- endswith/startswith 判断字符串是否以参数结尾/开头
>>> 'abc'.startswith('ab')
True
>>> 'abc'.startswith('abd')
False
>>> 'abc'.endswith('bc')
True
>>> 'abc'.endswith('cbc')
False
- format 格式化字符串
>>> 'my name is {}, i\'m {} years old'.format('xue', 30)
"my name is xue, i'm 30 years old"
>>> 'my name is {name}, i\'m {age} years old'.format(name='xue',age=30)
"my name is xue, i'm 30 years old"
>>> '|{name}|{age}|'.format(name='xue', age=30)
'|xue|30|'
>>> '|{name:10}|{age:10}|'.format(name='xue', age=30)
'|xue | 30|'
>>> '|{name:>10}|{age:<10}|'.format(name='xue', age=30)
'| xue|30 |'
- isalnum/isalpha/isdigit/isnumeric 判断字符串是否某类型的字符串
>>> 'abc123'.isalnum(), 'abc.123'.isalnum() (True, False) >>> 'abc123'.isalpha(), 'abc'.isalpha() (False, True) >>> '123'.isdigit(), '12.3'.isdigit() (True, False)
- join 使用字符串连接序列
- split/splitlines 分隔字符串为list
>>> dns = ['com', 'net', 'org']
>>> dns = ':'.join(dns)
>>> dns
'com:net:org'
>>> dns.split(':')
['com', 'net', 'org']
- lower/upper 将字符串转成小写/大写
>>> 'abcABC'.upper() 'ABCABC' >>> 'abcABC'.lower() 'abcabc'
- replace 替换字符串
>>> 'abcABCabcabac'.replace('abc', 'xue')
'xueABCxueabac'
- strip 去除字符串前后的空字符
>>> ' abc adb '.strip() 'abc adb'
练习:
查找字符串’abcdefabc’中第二个ab的位置
提示help(str.find)
字典
用途:存储用户信息
定义:
- 使用大括号包含
- 每个元素为key:value的格式
- 元素之间使用逗号分隔
>>> me = {'name': 'xue', 'age': 30}
>>> me
{'name': 'xue', 'age': 30}
访问与修改字典
访问
- 字典是key对value的映射,通过字典名[key]的方式访问字典中的元素
- 访问key必须存在,否则报错
>>> me = {'name': 'xue', 'age': 29, 'tel': 'xx'}
>>> me['name']
'xue'
>>> me['addr']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'addr'
修改
- 通过直接给 字典名[key]赋值来修改key对应的值
- 赋值时key在字典中不存在时则添加
>>> me['age'] = 30
>>> me['addr'] = '西安'
>>> me
{'name': 'xue', 'age': 30, 'tel': 'xx', 'addr': '西安'}
删除
- del 字典名[key]
- 删除key必须存在,否则报错
>>> del me['addr']
>>> me
{'name': 'xue', 'age': 30, 'tel': 'xx'}
>>> del me['add']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'add'
字典与列表的区别

字典的key
- 数字
- 整数
- 浮点数
- 字符串
- 布尔类型
- 列表 X
- 元组
- 子元素必须也不可变(“a”, “b”)
- ("a", ["b“]) X
- 字典 X
遍历字典
使用for访问字典中所有的元素
类型转换
可以通过函数dict将其他可遍历的类型转化为字典
参数: 将每个元素都两个子元素的序列组成的序列
结果:序列中的每个元素是字典的一个元素,子序列中第一个元素为key,第二个元素为value
>>> me = [('name', 'xue'), ('age', 29), ('tel', 'xxx')]
>>> me_dict = dict(me)
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx'}
字典常见操作
- 获取dict元素的数量
>>> me
[('name', 'xue'), ('age', 29), ('tel', 'xxx')]
>>> len(me_dict)
3
- 获取dict中key的最大值、最小值
>>> max(me_dict) 'tel' >>> min(me_dict) 'age'
- 判断元素是否在dict中(比较的key)
>>> 'name' in me_dict True >>> 'addr' not in me_dict True
练习
1、统计list中每个元素出现的次数
languages = ['python', 'java', 'python', 'c', 'c++', 'go', 'c#', 'c++', 'lisp', 'c', 'javascript', 'java', 'python', 'matlab', 'python', 'go', 'java'] 提示: 统计结果为element:count的形式,统计结果采用dict 从左到右依次遍历list中元素,判断是否在dict中,如果不在则将element存入dict并设置count为1,否则将dict中element对应的count加1后再存储到dict中
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Auth : xuegqcto@aliyun.com
'''
统计list中每个元素出现的次数
提示:
统计结果为element:count的形式,统计结果采用dict
从左到右依次遍历list中元素,判断是否在dict中,如果不在则将element存入dict并设置count为1,否则将dict中element对应的count加1后再存储到dict中
'''
languages = ['python', 'java', 'python', 'c', 'c++', 'go', 'c#', 'c++', 'lisp', 'c', 'javascript', 'java', 'python', 'matlab', 'python', 'go', 'java']
stat = {}
for language in languages:
if language in stat:
stat[language] += 1
else:
stat[language] = 1
print(stat)
结果:
{'python': 4, 'java': 3, 'c': 2, 'c++': 2, 'go': 2, 'c#': 1, 'lisp': 1, 'javascript': 1, 'matlab': 1}
2、统计文章中每个英文字母出现的次数
article = 'I was not delivered unto this world in defeat, nor does failure course in my veins. I am not a sheep waiting to be prodded by my shepherd. I am a lion and I refuse to talk, to walk, to sleep with the sheep. I will hear not those who weep and complain, for their disease is contagious. Let them join the sheep. The slaughterhouse of failure is not my destiny.'
提示:判断是否为英文单词
if (element > ‘a’ and element < ‘z’) or (element > ‘A’ and element < ‘Z’)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Auth : xuegqcto@aliyun.com
'''
统计文章中每个英文字母出现的次数
if (element > ‘a’ and element < ‘z’) or (element > ‘A’ and element < ‘Z’)
'''
article = '''I was not delivered unto this world in defeat, nor does failure course in my veins.
I am not a sheep waiting to be prodded by my shepherd. I am a lion and I refuse to talk, to walk,
to sleep with the sheep. I will hear not those who weep and complain, for their disease is contagious.
Let them join the sheep. The slaughterhouse of failure is not my destiny.'''
stat = {}
for chr in article:
if (chr > 'a' and chr < 'z') or (chr > 'A' and chr < 'Z'):
if chr in stat:
stat[chr] += 1
else:
stat[chr] = 1
print(stat)
结果:
{'I': 5, 'w': 8, 's': 20, 'n': 17, 'o': 24, 't': 23, 'd': 13, 'e': 39, 'l': 12, 'i': 20, 'v': 2, 'r': 13, 'u': 8, 'h': 17, 'f': 6, 'c': 3, 'm': 7, 'y': 5, 'p': 8, 'g': 3, 'b': 2, 'k': 2, 'L': 1, 'j': 1, 'T': 1}
字典函数
- clear 清空dict中的元素
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'xian'}
>>> id(me_dict)
1555178797600
>>> me_dict = {}
>>> me_dict
{}
>>> id(me_dict)
1555179083888
>>> me_dict = {'name': 'xue', 'age': 29}
>>> id(me_dict)
1555178912864
>>> me_dict.clear()
- copy 复制dict中的所有元素到新dict中并返回
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'xian'}
>>> me_dict_2 = me_dict
>>> me_dict_2['addr'] = 'yyy'
>>> me_dict_2
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'yyy'}
>>> me_dict_3 = me_dict.copy()
>>> me_dict_3
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'yyy'}
>>> me_dict_2['addr'] = 'ttt'
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'ttt'}
>>> me_dict_2
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'ttt'}
>>> me_dict_3
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'yyy'}
- fromkeys 根据序列生成dict,序列中所有元素作为key,value为fromkeys的第二个参数,默认为None
>>> dict.fromkeys(['name', 'age', 'addr', 'tel'])
{'name': None, 'age': None, 'addr': None, 'tel': None}
>>> dict.fromkeys(['name', 'age', 'addr', 'tel'], '')
{'name': '', 'age': '', 'addr': '', 'tel': ''}
- get 返回dict中key对应的值,若key不存在则返回默认值
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx'}
>>> print(me_dict.get('name'))
xue
>>> print(me_dict.get('addr'))
None
>>> print(me_dict.get('addr', 'xian'))
xian
- items 将dict转化为由每个元素均为两个子元素的序列组成的dict_items,可通过list将dict_items转化为list
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': '18012341234', 'addr': 'xian'}
>>> list(me_dict.items())
[('name', 'xue'), ('age', 29), ('tel', '18012341234'), ('addr', 'xian')]
>>> for e in me_dict.items():
... print(e)
...
('name', 'xue')
('age', 29)
('tel', '18012341234')
('addr', 'xian')
>>> for k, v in me_dict.items():
... print(k, v)
...
name xue
age 29
tel 18012341234
addr xian
- keys 返回dict中所有的key组成的dict_keys
- values 返回dict中所有value组成的dict_values
>>> list(me_dict.keys()) ['name', 'age', 'tel', 'addr'] >>> list(me_dict.values()) ['xue', 29, '18012341234', 'xian']
- pop 通过key弹出字典中的元素,未设置默认值,当key不存在则报错,否则返回默认值
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': '18012341234', 'addr': 'xian'}
>>> me_dict.pop('addr')
'xian'
>>> me_dict.pop('addr', 'beijing')
'beijing'
- popitem 返回dict中的某个元素组成的元组(key, value)
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': '18012341234'}
>>> me_dict.popitem()
('tel', '18012341234')
>>> me_dict
{'name': 'xue', 'age': 29}
- setdefault 设置dict中key的默认值(key不存在则设置)并返回dict中key的当前值
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx'}
>>> print(me_dict.setdefault('addr', 'xian'))
xian
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'xian'}
>>> print(me_dict.setdefault('addr', 'beijing'))
xian
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx', 'addr': 'xian'}
- update 通过dict批量更新或添加dict中的值
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': 'xxx'}
>>> me_dict.update({'tel': '18012341234', 'addr': 'xian'})
>>> me_dict
{'name': 'xue', 'age': 29, 'tel': '18012341234', 'addr': 'xian'}
练习:
1、使用get替换languages统计中的not in
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Auth : xuegqcto@aliyun.com
'''
统计list中每个元素出现的次数
提示:
统计结果为element:count的形式,统计结果采用dict
从左到右依次遍历list中元素,判断是否在dict中,如果不在则将element存入dict并设置count为1,否则将dict中element对应的count加1后再存储到dict中
'''
languages = ['python', 'java', 'python', 'c', 'c++', 'go', 'c#', 'c++', 'lisp', 'c', 'javascript', 'java', 'python', 'matlab', 'python', 'go', 'java']
stat = {}
for language in languages:
stat[language] = stat.get(language, 0) + 1
print(stat)
2、使用setdefault替换article统计中的not in
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Auth : xuegqcto@aliyun.com
'''
统计文章中每个英文字母出现的次数
if (element > ‘a’ and element < ‘z’) or (element > ‘A’ and element < ‘Z’)
'''
article = '''I was not delivered unto this world in defeat, nor does failure course in my veins.
I am not a sheep waiting to be prodded by my shepherd. I am a lion and I refuse to talk, to walk,
to sleep with the sheep. I will hear not those who weep and complain, for their disease is contagious.
Let them join the sheep. The slaughterhouse of failure is not my destiny.'''
stat = {}
for chr in article:
if (chr > 'a' and chr < 'z') or (chr > 'A' and chr < 'Z'):
stat[chr] = stat.setdefault(chr, 0) + 1
print(stat)
3、获取出现次数最多的TOP 10 字符
提示:list可以排序,并根据list中元素中索引为1(元组)的值进行排序
作业:用户管理
浙公网安备 33010602011771号