python基础语法之【字符串常用操作】

其他文章:python基础语法之【基本数据类型】

字符串常用操作方法

python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等

一、去空格

str.strip():删除字符串两边的指定字符,括号的写入指定字符,默认空格
str.lstrip():删除字符串左边的指定字符,括号的写入指定字符,默认空格
str.rstrip():删除字符串右边的指定字符,括号的写入指定字符,默认空格

str1 = '  hello, world!  '#左右有空格
print(str1.strip())  #删掉左右两侧空格
>>>hello, world!
str2='123hello, world!123'
print(str2.lstrip('123')) #删除左侧123
>>>hello, world!123
print(str2.rstrip('123')) #删除右侧123
>>>123hello, world!
print(str2)
>>>123hello, world!123   #字符串是不可变类型,除非删除之后重新赋值给str2
二、按索引、切片、取值(只能取)

必须注意,因为字符串是不可变对象,无法原处修改,所以无论是索引取值还是分片操作,都会创建新字符串对象。

#按索引(切片)取值
str1='hello, world!'
print(str1[1])

>>>e
print(str1[1:3])
>>>el
print(str1[-1::-1])  #字符串取反
>>>!dlrow ,olleh  
三、查找字符串

str.index 和str.find 功能相同,区别在于find()查找失败会返回-1,不会影响程序运行。而index方法中,str不在 string中会报一个异常。

str1='hello python'
print(str1.index('o')) #从下标0开始,查找在字符串里第一个出现的子串:返回结果4
print(str1.index('o',5))#从下标5开始,查找在字符串里第一个出现的子串:返回结果10

#语法:str.find(str, beg=0, end=len(string))
# 如果值存在,返回索引位置,不存在返回-1
print(str1.find('l')) #从下标0开始,查找在字符串里第一个出现的子串:返回结果2
print(str1.find('o',6)) #从下标6开始,查找在字符串里第一个出现的子串:返回结果10
print(str1.find('4')) # 查找不到返回-1
四、字符串替换
str1='me name is jasn'
print(str1.replace("jasn","kang")) #如果查找到jasn,则替换为kang

>>>me name is kang
print(str1.replace('python','c##'))#如果值不存在,则不替换
>>>me name is jasn
print(str1)   #无法原处修改
>>>me name is jasn
五、字符串分割

一、split方法
方法:str.split(self,sep,maxsplit) #默认拆分(从左往右)
作用:找出字符串s中的sep字符,将sep当做分隔依据拆分该字符串s,返回一个拆分开来的列表
参数:sep:分隔依据 字符串,maxsplit:最大拆分次数,不写默认全部
二、rsplit方法
用法和split一致,默认从右往左
三、 splitlines方法
按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

#str.split默认从左往右
str1 = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print(str1.split())  # 以空格为分隔符,包含 \n
>>>['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
print(str1.split(' ', 1))  # 以空格为分隔符,分隔成两个(从左到右)
>>>['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
print(str1.split('e')) # 按输入字符分割
>>>['Lin', '1-abcd', 'f \nLin', '2-abc \nLin', '4-abcd']
#str.rsplit
print(str1.rsplit('c',1))#从右往左,分割1次
>>>['Line1-abcdef \nLine2-abc \nLine4-ab', 'd']
print(str1.splitlines()) #根据换行执行方法
>>>['Line1-abcdef ', 'Line2-abc ', 'Line4-abcd']

六、 join()方法

Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

print('a'.join('大家好'))

>>>大a家a好
str1 = "-"
seq = ("a", "b", "c") #可迭代对象必须都是字符串
print( str1.join( seq ))
>>a-b-c
七、字符串个数统计

Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

a='hello world'
print(a.count('l'))
>>>3
八、判断字符串是否由数字组成

Python isdigit() 方法检测字符串是否只由数字组成。
语法:str.isdigit()
返回值:如果字符串只包含数字则返回 True 否则返回 False。

while True:
    password=input('>>请输入数字密码:')
    if password.isdigit():
        break
    else:
        print('请输入数字密码')
九、字符串大小写转换
#coding=utf-8
"""
字符串常用操作
Version: 0.1
Author: jasn
Date: 2019-12-15
"""
str1 = 'hello, world!'
print('字符串内容为:%s'%str1)
print('字符串的长度是:', len(str1))
print('单词首字母大写: ', str1.title())
print('字符串变大写: ', str1.upper())
print('字符串是不是大写: ', str1.isupper())
print('字符串是不是以hello开头: ', str1.startswith('hello'))
print('字符串是不是以hello结尾: ', str1.endswith('hello'))
print('字符串是不是以感叹号开头: ', str1.startswith('!'))
print('字符串是不是以感叹号结尾: ', str1.endswith('!'))
print('字符串转化为标题:'str1.title())
str2 = '- \u91d1\u978d\u5c11\u5e74'
str3 = str1.title() + ' ' + str2  #字符串相加
print((str3+"\n")*2 )  #字符串相乘
发布了46 篇原创文章 · 获赞 37 · 访问量 4543

猜你喜欢

转载自blog.csdn.net/weixin_42444693/article/details/103568553