python字符串的操作全集(一)创建、切片、分割等
2020-07-14 06:35
671 查看
这里写目录标题
- 1. 字符串创建
- 2. 字符串切片
- 3. 字符串添加元素
- 4.字符串分割
- 4.1 partition(sub):
- 4.2 rpartition(sub):
- 4.3 spilit(sep=None,maxsplit=-1):
- 4.4 splitlines(keepends):
1. 字符串创建
str1='I Love China' #创建字符串 print(str1) #输出整个字符串 print(str1[4]) #输出指定索引字符
输出结果:
I Love China
v
2. 字符串切片
str2=str1[:6] print(str2) print('str2的ID:',id(str2)) #输出str2的地址
输出结果:
I Love
str2的ID: 10345728
3. 字符串添加元素
str2=str2+' you' print('str2:',str2) print('str2的ID:',id(str2)) #可以看出,str2地址已经发生了变化,并不是原来的str2了
输出结果:
str2: I Love you
str2的ID: 16663480
注: 可以看出str2的ID分别为: 10345728和16663480,前后已经发生了变化,说明字符串的名字虽然相同,但指向已经发生了变化,不是原来的字符串了。
4.字符串分割
4.1 partition(sub):
找到字符串sub,把字符串分成3个元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’ ‘,’ ')
temp17='345studyC语言单片机' print(temp17.partition('study')) print(temp17.partition('studx'))
输出结果:
(‘345’, ‘study’, ‘C语言单片机’)
(‘345studyC语言单片机’, ‘’, ‘’)
4.2 rpartition(sub):
从右边找字符串sub,把字符串分成3个元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(’ ‘,’ ',‘原字符串’)
temp3='345studyC语言单片机' print(temp3.rpartition('study')) print(temp3.rpartition('studx'))
输出结果:
(‘345’, ‘study’, ‘C语言单片机’)
(’’, ‘’, ‘345studyC语言单片机’)
4.3 spilit(sep=None,maxsplit=-1):
以sep为分隔符,若无sep默认是以空格为分隔符切片字符串,如果maxsplit设置了参数,则仅分隔maxsplit个字符串,返回切片后的子字符串拼接的列表
temp4='pig dog cat fish fish' print(temp4.split()) #无参数,以空格为分隔符 print(temp4.split('i')) #以‘i’为分隔符
输出结果:
[‘pig’, ‘dog’, ‘cat’, ‘fish’, ‘fish’]
[‘p’, ‘g dog cat f’, ‘sh f’, ‘sh’]
4.4 splitlines(keepends):
按照‘\n’分隔,返回一个包含各行作为元素的列表,如果keepends参数为True,则保留换行符
temp5='''好好学习 天天向上 成为祖国的花朵''' print(temp5.splitlines()) print(temp5.splitlines(keepends=True))
输出结果:
[‘好好学习’, ‘天天向上’, ‘成为祖国的花朵’]
[‘好好学习\n’, ‘天天向上\n’, ‘成为祖国的花朵’]
相关文章推荐
- Python string字符串操作 encode decode 切片 分割 合并
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- python 字符串的切片操作 200310
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python切片操作去除字符串首尾的空格
- 0714学习笔记list常用操作索引(index)和切片(slice) 字符串的方法分割split和连接join
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(截取/替换/查找/分割)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- 黄聪:Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python字符串操作全集(四)查询、索引和替换