python——字符串常用方法

导读:本篇文章讲解 python——字符串常用方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、split:字符串分割

1、分割后为列表

str1='heloworld'
print(str1.split('l'))			['he', 'owor', 'd']

str1='hellloworld'
print(str1.split('ll'))         ['he', 'loworld']

str1='aaabcd'
print(str1.split('a'))			['', '', '', 'bcd']
print(str1.split('aa'))			['', 'abcd']
print(str1.split('aaa'))		['', 'bcd']
print(str1.split('aaaa'))		['aaabcd']

二、strip:去除字符串头尾指定的字符(lstrip、rstrip)

1、用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
2、该方法只能删除开头或者是结尾的字符,不能删除中间部分的字符。
3、返回值为移除字符串头尾指定的字符生成的新的字符串

str2='helloworld'
print(str2.strip('d'))      	helloworl
print(str2.strip('world')) 		he

str2="  000120abc021000 \n"  
print(str2.strip())             000120abc021000

删除字符串开头和结尾指定为0的字符
str2="000120abc021000"
print(str2.strip('0'))          120abc021

删除字符串开头指定为0的字符
print(str2.lstrip('0'))         120abc021000

删除字符串结尾指定为0的字符
print(str1.rstrip('0'))         000120abc021

三、replace:替换

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

str3='helloworld'
print(str3.replace('l','中'))    	替换所有的  he中中owor中d
print(str3.replace('l','中',1))      替换第一个  he中loworld

四、format:字符串的格式化

1、第一种方式
s='o'
str4=f'hell{s}world'
print(str4)

2、第二种方式
s='o'
str4='hell{}world'.format(s)
print(str4)

五、index:获取字符串中某个元素的索引,元素不存在,会抛出异常

str8='helloworld'
print(str8.index('r'))
#print(str8.index('i')) 会抛出异常:ValueError: substring not found

六、find:获取字符串中某个元素的索引,元素不存在,返回-1

str7='helloworld'
print(str7.find('r'))
print(str7.find('i'))   #元素不存在,返回-1

七、upper:将字符串中的字母变为大写字母

str9='helloworld'
print(str9.upper())		HELLOWORLD

八、lower:将字符串中的字母变为小写字母

str10='Helloworld'
print(str10.lower())	helloworld

九、count:统计字符串中指定元素的个数

str12='helloworld'
print(str12.count('p'))		0

十、join:字符串的拼接

方法用于将序列中的元素以指定的字符连接生成一个新的字符串
返回通过指定字符连接序列中元素后生成的新字符串。

例1

str13='helloworld'
lis=''.join(str13)
print(lis)				helloworld
print(type(lis))		<class 'str'>

例2

lis=[1,2,3,4,5]
lis1=','.join(lis)
print(lis1)	
抛出异常:TypeError: sequence item 0: expected str instance, int found
列表中的元素为只有为字符串类型的数据才能进行拼接

十一、startswith:检查字符串是否以 “xxx” 开头

检查字符串是否以 “xxx” 开头;如果字符串以指定的值开头,则 startswith() 方法返回 True,否则返回 False。
语法:
string.startswith(value, start, end)
value:必需。检查字符串是否以其开头的值。
start:可选。整数,规定从哪个位置开始搜索。
end:可选。整数,规定结束搜索的位置。

案例1:检查字符串是否以__开头

str6='__helloworld'
def func():
    if not str6.startswith('__'):
        return '1'
    else:
        return '2'
res=func()
print(res)

案例2:检查字符串str6_2中从索引1到索引10中,是否已‘we’开头

str6_1='Hello, welcome to my world'
str6_2=str6_1.startswith('we',1,10)
print(str6_2)

十二、encode:编码

str14='helloworld'
str14_1=str14.encode(encoding='utf8')
print(str14_1)			b'helloworld'

十三、decode:解码

str15=str14_1.decode(encoding='utf8')
print(str15)			helloworld

十四、isdigit:检测字符串是否只由数字组成。

如果字符串只包含数字则返回 True 否则返回 False。

def func(arg):
    if not arg.isdigit():
        return '不是数字'
    else:
        return '是数字'

print(func('123123'))
print(func('1zilv23'))
print(func('zilv'))

十五、endswith:检查字符串是否以 “xxx” 结尾

检查字符串是否以 “xxx” 结尾;如果字符串以指定的值结尾,则 endswith() 方法返回 True,否则返回 False。
语法:
string.endswith(value, start, end)
value:必需。检查字符串是否以其结尾的值。
start:可选。整数,规定从哪个位置开始搜索。
end:可选。整数,规定结束搜索的位置。

str6='__helloworld__'
def func():
    if not str6.endswith('__'):
        return '1'
    else:
        return '2'
res=func()
print(res)

十六、len:计算字符串的长度

str16='helloworld'
print(len(str16))

十七、S.isalnum() #是否全是字母和数字,并至少有一个字符

def func(arg):
    if arg.isalnum():
        return '全是字母和数字'
    else:
        return '不全是字母和数字'

print(func('helloworld'))
print(func('helloworld_'))

十八、S.isalpha() #是否全是字母,并至少有一个字符

def func(arg):
    if arg.isalpha():
        return '全是字母'
    else:
        return '不全是字母'

print(func('helloworld'))
print(func('helloworld_'))

十九、S.isspace() #是否全是空白字符,并至少有一个字符

def func(arg):
    if arg.isspace():
        return '全是空白字符'
    else:
        return '不全是空白字符'

print(func('helloworld'))
print(func(' '))

二十、S.islower() #S中的字母是否全是小写

二十一、S.isupper() #S中的字母是否全是大写

二十二、S.istitle() #S是否是首字母大写的

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/74288.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!