【Python-字符串应用】

在生活中,字符串是很常见的,如人的名字、网站地址、文本文件中的内容等。任何编程语言来说,字符串都是最重要的数据类型之一。


字符串的应用

str.lower() 将str字符串全部转成小写字母,结果为一个新的字符串
str.upper() 将str字符串全部转成大写字母,结果为一个新的字符串
str.spilt(sep=None) 把str按照指定的分隔符sep进行分隔,结果为列表类型
str.count(sub) 结果为sub这个字符串在str中出现的次数
str.find(sub) 查询sub这个字符串在str是否存在,如果不存在结果为-1,如果存在,结果为首次粗线的索引
str.index(s) 功能与find()相同,区别在于查询的子串sub不存在时,程序报错
str.startswith(s)

查询字符串是否以子串s开头

str.endswith(s) 查询字符串是否以子串s结尾

1.将含有大小写的字符串转换大小写字母:如下 

p1='Hello World!'
new_p1=p1.lower()#全部转换为小写字母
print(p1,new_p1)

print(p1.upper())#全部转换为大写字母


2.字符串的分隔

s_email='[email protected]'
lst=s_email.split('@')#@为分隔符
print('邮件名:',lst[0],'邮件服务器域名:',lst[1])

3.字符串的统计

print(p1.count('W'))#统计共有多少个w

4.字符串的查找,并区分find()与index()的区别

print(p1.find('o'))#查找第一个o的位置
print(p1.find('p'))#不存在str中,返回值为-1

print(p1.index('o'))#查找第一次o的位置
print(p1.index('p'))

5.字符串开头与结尾的查询

print(p1.startswith('H'))#判断str首位是否为H
print(p1.startswith('p'))
print(p1.endswith('!'))#判断结尾是否为!
print(p1.endswith('l'))

希望对你有所帮助!

猜你喜欢

转载自blog.csdn.net/qq_72356432/article/details/125822098