您的位置:首页 > 编程语言 > Python开发

python字符串的操作全集(一)创建、切片、分割等

2020-07-14 06:35 671 查看

这里写目录标题

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’, ‘成为祖国的花朵’]

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐