04 字符串方法

本文详细介绍了Python中的字符串方法,包括替换、大小写转换、切割、拼接和查找等。同时,讲解了字典和集合的操作,如定义、增删改查以及相关运算。此外,还涉及到了编码与解码的基础知识。通过实例展示了如何进行字符串编码和解码,以及散列类型的特性和可变对象与不可变对象的区别。
摘要由CSDN通过智能技术生成

04 字符串方法

基本

功能方法
替换字符串.replace(替换值,替换目标,次数)
大写字符串.upper()
小写字符串.lower()
首字母大写字符串.capitalize()
标题形式字符串.title()

str1 = 'hello world'

# replace
>>> str1.replace('l','k')
'hekko workd'
>>> str1
'hello world'




# 大写
>>> str1.upper()
'HELLO WORLD'
#小写
>>> str1.lower()
'hello world'



# 首字母大写
>>> str1.capitalize()
'Hello world'

# 标题形式
>>> str1.title()
'Hello World'

切割、拼接与查找

功能方法说明
去掉两边空格.strip() —— lstrip()或rstrip()
切割str2.split(切割符,次数)
拼接‘拼接符’.join(字符串)
查找元素位置 1字符串.index(查找值,下标开始)报错:未找到元素
查找元素位置 2字符串.find(查找值,下标开始)返回-1:未找到元素
str2 = '  hello world this is python   '
# 去掉两边空格
>>> str2.strip()
'hello world this is python'
# 切割 
>>> str2.split('o',2)
['  hell', ' w', 'rld this is python   ']


# 拼接 _ 需要先 split 才能 join
>>> str2.split('this')
['  hello world ', ' is python   ']
>>> 'he'.join(str2.split('this'))
'  hello world he is python   '


# 查找元素位置 
>>> str2.index('l',11) 
11
>>> str2.index('l',100)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    str2.index('l',100)
ValueError: substring not found


# 查找元素位置 2 
>>> str2.find('l',11)     
11
>>> str2.find('l',100)     
-1


判断与转义

功能方法
判断全是中文或者字母组成字符串.isalpha()
数字isdigit()
大写isupper()
小写islower()
转义换行\n(在print函数里才起作用)
水平制表符\t
往前退一格\b(cmd起作用)
系统提示音\a(cmd起作用)
空格\0
取消转义\
统一取消转义r’字符串’

判断


# 全是中文或者字母组成 
>>> 'hello world'.isalpha()
False #字符串包含空格
>>> 'helloworld'.isalpha()
True
>>> '你好世界'.isalpha()
True

# 数字
>>> '123'.isdigit()
True
>>> '123a'.isdigit()
False


# 大写
>>> "HELLO WORLD".isupper()
True
>>> "HELLOWORLD".isupper()
True
>>> "Hello World".isupper()
False



# 小写
>>> "hello world".islower()
True
>>> "Hello World".islower()
False
>>> "HELLO WORLD".islower()
False
>>> "HELLOWORLD".islower()
False

转义

>>> print('hello\npython')
hello
python
>>> print('hello\tpython')
hello	python
>>> print('hello\bpython')
hellpython
>>> print('hello\apython') #cmd 会有系统提示音
hellopython
>>> print('hello\0python')
hello python
>>> print('hello\\npython')
hello\npython
>>> print(r'hello\npython')
hello\npython

字典

功能方法说明
定义-1{键1:值1,键2:值2}
定义-2dict(键1=值1,键2=值2)
取值字典[key]
字典.setdefault(键,value)
查值1dic[key]报错:不存在的键
查值2dic.get(key)返回空:不存在
改值1dic[key] = value无则增,有则改
改键值2dic.update({key:value, key:value})无则增,有则改
删1dic.pop(key)删除对应键的键值对数据
删2dic.popitem()后添加先删除
删3dic.clear()>全部
获取所有的键名dic.keys()
获取所有的值dic.values()
获取所有的键值dic.items()
# 定义
dic_1 = {'name':'william','age':'23','country':'Indonesia'}
dic_2 = dict(name='william',age=23,country='Indonesia')

# 取值
>>> dic_1["name"]
'william'

# 增
>>> dic_1
{'name': 'william', 'age': '23', 'country': 'Indonesia', 'study': 'xiamen'}

# 查
>>> dic_1['name']
'william'
>>> dic_1.get('name')
'william'

# 改
>>> dic_1['name'] = 'Lie Pin'
>>> dic_1
{'name': 'Lie Pin', 'age': '23', 'country': 'Indonesia', 'study': 'xiamen'}

>>> dic_1.update({'age':'40','study':'indonesia', 'job':'no'})
>>> dic_1
{'name': 'Lie Pin', 'age': '40', 'country': 'Indonesia', 'study': '
indonesia', 'job': 'no'}

# 删除
>>> dic_1.pop('job')
'no'
>>> dic_1
{'name': 'Lie Pin', 'age': '40', 'country': 'Indonesia', 'study': 'indonesia'}

>>> dic_1.popitem()
('study', 'indonesia')
>>> dic_1
{'name': 'Lie Pin', 'age': '40', 'country': 'Indonesia'}
>>> dic_1.clear()
>>> dic_1
{}

# 获取
>>> dic_1 = {'name':'william','age':'23','country':'Indonesia'}
>>> dic_1.keys()
dict_keys(['name', 'age', 'country'])
>>> dic_1.values()
dict_values(['william', '23', 'Indonesia'])
>>> dic_1.items()
dict_items([('name', 'william'), ('age', '23'), ('country', 'Indonesia')])

集合

项目项目说明
特征去重
无序
定义set(‘字符串’)
运算交集
并集
差集
增加单个集合.add(‘值’)
批量集合.update({值1,值2,值3})
删除随机集合.pop()
指定集合.remove(值)
判断交集?集合1.isdisjoint(集合2)
set2在set1的下级集合2.issubset(集合1)
set1包含set3的值集合1.issuperseet(集合3)

特征

# 去重
>>> set1 = {1,2,3,4,1,2,3,4}
>>> set1
{1, 2, 3, 4}

# 无序
>>> set2 = {1,'a','b',2,3}
>>> set2
{1, 2, 3, 'b', 'a'}

运算

set1 = {1,2,3,4,5,7}
set2 = {1,3,5,7}
set3 = {'a','b'}

# 交集 &
>>> print(set1 & set2)
{1, 3, 5, 7}

# 并集  |
>>> print(set1 | set3)
{'b', 1, 2, 3, 4, 5, 'a', 7}

# 差集 -
>>> print(set1 - set2)
{2, 4}

增加和删除

set1 = {1,2,3,4}
# 单个增加
>>> set1.add('a')
>>> set1
{1, 2, 3, 4, 'a'}

#批量增加
set1.update('b','c','d')
>>> set1.update('b','c','d')
>>> set1
{'b', 1, 2, 3, 4, 'a', 'd', 'c'}


# 删除
>>> set1
{'b', 1, 2, 3, 4, 'a', 'd', 'c'}
>>> set1.pop()
'b'
>>> set1
{1, 2, 3, 4, 'a', 'd', 'c'}

# 制定删除
>>> set1
{1, 2, 3, 4, 'a', 'd', 'c'}
>>> set1.remove('d')
>>> set1.remove('a')
>>> set1
{1, 2, 3, 4, 'c'}

判断交叉 | 层级

set1 = {1,2,3,4,5,6}
set2 = {4,5,6}
set3 = {3,4,5}

>>> set1.isdisjoint(set2) # 没有交集返回true
False

>>> set2.issubset(set1)
True

>>> set1.issuperset(set2)
True

其他

功能身份运算符
A是B?is
否(A是B?)is not
A在B?in
否(A在B?)not in

注意:python当中存在内存池,范围[-5,256]

>>> a = 300
>>> b = 300
>>> a == b
True
>>> a is b
False
 
>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True

优先级顺序

运算符描述
**幂运算
+、-一元运算符(正负号)
*、/、%算术运算符(乘、除、取余)
+、-(加减)
<、>、<=、>=比较运算符
==、!=
=、%=、/=、-=、+=、*=、**=赋值运算符
is、is not身份运算符
in、not in成员运算符
not > and > or逻辑运算符

BONUS

解码和编码

功能方法
编码字符串.encode(encoding=‘utf-8’)
解码字符串.decode(encoding=‘utf-8’)
>>> "蔡汶桦".encode(encoding="utf-8")
b'\xe8\x94\xa1\xe6\xb1\xb6\xe6\xa1\xa6'
>>> "蔡汶桦".encode("utf-8")
b'\xe8\x94\xa1\xe6\xb1\xb6\xe6\xa1\xa6'
>>> "蔡汶桦".encode()
b'\xe8\x94\xa1\xe6\xb1\xb6\xe6\xa1\xa6'
>>> b'\xe8\x94\xa1\xe6\xb1\xb6\xe6\xa1\xa6'.decode()
'蔡汶桦'
>>> b'\xe8\x94\xa1\xe6\xb1\xb6\xe6\xa1\xa6'.decode(encoding='UTF-8')
'蔡汶桦'

散列类型

类型实例
散列类型字典
集合
顺序类型列表
元组
字符串

可变对象 | 不可变对象

发展规律实例
可变对象修改>地址不变list、dict、set
不可变对象修改>地址变数值、str、元组
>>> lis1 = [1,2,3]
>>> id(lis1)
2118046143112 # 留意这里
>>> lis1.append(4)
>>> lis1
[1, 2, 3, 4]
>>> id(lis1)
2118046143112 # 留意这里

下载:练习题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值