string内建函数

1 字符串内建函数

1.1 转换类函数

'''

字符串内建函数

capitalize():将字符串第一个字母转换为大写字母

title():将每个单词的首字母大写

 upper() :将字符串全部转换为大写

 lower():将字符串全部转换为小写

 istitle():方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

 如果字符串中所有的单词拼写首字母是否为大写,且其他字母为小写则返回 True,否则返回 False.

'''

 1 import random
 2 
 3 message='this is a beautiful city'
 4 
 5 msg=message.capitalize()
 6 
 7 print("%s--message.capitalize()="%message,msg)#将字符串第一个字母转换为大写字母
 8 
 9 msg=message.title()
10 
11 print("%s--message.title()="%message,msg)#将每个单词的首字母大写
12 
13 result=msg.istitle()
14 
15 print("%s--message.istitle()="%message,result)#检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
16 
17 msg=message.upper()#将字符串全部转换为大写
18 
19 print("%s--message.upper()="%message,msg)
20 
21 msg=message.lower()#将字符串全部转换为小写
22 
23 print("%s--message.lower()="%message,msg)

 1 #随机生成4个验证码
 2 
 3 s='ABCDEFGHIJKLMNOPQRSTUVWXYXZabcdefghijklmnopqrstuvwxyz0123456789'
 4 
 5 print(len(s))
 6 
 7 code=''
 8 
 9 for i in range(4):
10 
11     ran=random.randint(0,len(s)-1)
12 
13     code+=s[ran]
14 
15  
16 
17 print(code)
18 
19 #输入验证码成功则提示输入正确,错误则提示错误
20 
21 user_input=input('请输入验证码:')
22 
23 if user_input.lower()==code.lower():
24 
25     print('验证码输入正确')
26 
27 else:
28 
29   print("验证码输入错误")

 

1.2 查找类函数

'''

查找相关

find():方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,

则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

str.find(str, beg=0, end=len(string))

参数

str -- 指定检索的字符串

beg -- 开始索引,默认为0。

end -- 结束索引,默认为字符串的长度。

 

rfind():从右侧检索位置, 返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

str.rfind(str, beg=0 end=len(string))

参数

str -- 查找的字符串

beg -- 开始查找的位置,默认为 0

end -- 结束查找位置,默认为字符串的长度。

 

index():和find()一样,只是找不到会报异常

str.index(str, beg=0, end=len(string))

参数

str -- 指定检索的字符串

beg -- 开始索引,默认为0。

end -- 结束索引,默认为字符串的长度。

 

rindex():返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,

str.rindex(str, beg=0 end=len(string))

参数

str -- 查找的字符串

beg -- 开始查找的位置,默认为0

end -- 结束查找位置,默认为字符串的长度。

 

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

str.replace(old, new[, max])

参数

old -- 将被替换的子字符串。

new -- 新字符串,用于替换old子字符串。

max -- 可选字符串, 替换不超过 max次

'''

 1 s1='good secuqry sundy shaine'
 2 
 3 result= 'c' in s1
 4 
 5 print("%s---'c' in s1="%s1,result)
 6 
 7 position=s1.find("s") #返回-1表示没找到
 8 
 9 print("%s---s1.find('s')="%s1,position)       #如果可以找到则返回字符第一次出现的位置
10 
11 p=s1.find('s',position+1,len(s1)-2)
12 
13 print("%s---.find('s',position+1,len(s1)-2)="%s1,p)

1 info = 'zcdfgabcadfgabcdfg'
2 
3 res=info.find('dfg',10)
4 
5 print("%s---info.find('dfg',10)="%info,res)  # 从下标1开始,查找在字符串里第1个出现的子串:返回结果15

 

url='https://timgsa.baidu.com/img/timg.jpg'

p=url.rfind('/') #从右侧检索位置, 返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

print("%s\turl.rfind('/')="%url,p)

filename=url[p+1:]

print("%s\turl[p+1:]="%url,filename)

 

p=url.rfind('.')

print("%s\turl.rfind('.')="%url,p)

name=url[p:]

print("%s\turl[p:]="%url,name)

1 str = "this is really a string example....wow!!!";
2 
3 substr = "is";
4 
5 print str.rfind(substr, 1, 10);

 1 str='399fgdhj341fgs345'
 2 
 3 position=str.index('fg',2,-2)
 4 
 5 print("%s----str.index('fg',2,-2)="%str,position)
 6 
 7  
 8 
 9 p1=str.rindex("fg",2,-2)#返回子字符串 str 在字符串中最后出现的位置,如果没有匹配的字符串会报异常,
10 
11 print("%s----strrindex('fg',2,-2)="%str,p1)

1 date='2020/10/2'
2 
3 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
4 
5 print("%s---date.replace('/','-')="%date,date.replace('/',"-"))

1 str = "this is string example....wow!!! this is really string";
2 
3 res=str.replace("is", "was", 3)
4 
5 print("%s---str.replace('is', 'was', 3)="%str,res) ;#thwas was string example....wow!!! thwas is really string

1.3 decode(),encode(),startswith(),endswith() 

'''

字符串内建函数

encode

str.encode(encoding='UTF-8',errors='strict')

参数

encoding -- 要使用的编码,如"UTF-8"。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。

其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

 

decode

str.decode(encoding='UTF-8',errors='strict')

参数

encoding -- 要使用的编码,如"UTF-8"。

errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。

其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

 

编码:网络应用 中文设计编码解码

 

startswith()方法用于检查字符串是否是以指定子字符串开头,

如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

方法语法:

str.startswith(str, beg=0,end=len(string));

参数

str -- 检测的字符串。

strbeg -- 可选参数用于设置字符串检测的起始位置。

strend -- 可选参数用于设置字符串检测的结束位置。

 

endswith()方法用于判断字符串是否以指定后缀结尾,

如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

方法语法:

str.endswith(suffix[, start[, end]])

参数

suffix -- 该参数可以是一个字符串或者是一个元素。

start -- 字符串中的开始位置。

end -- 字符中结束位置。

'''

 1 msg='欢迎你来到学习乐园'
 2 
 3 res=msg.encode('utf-8')#编码
 4 
 5 print("%s---msg.encode('utf-8')="%msg,res)
 6 
 7  
 8 
 9 #解码
10 
11 m=res.decode('utf-8')
12 
13 print("%s---res.decode('utf-8')="%msg,m)

#startswith endswith 返回布尔值

#startswith:判断是否以XX开头 endswith:判断是否以XX结尾

 

#只上传doc文件

1 filename='笔记.doc'
2 
3 res=filename.endswith('doc') #filename是否以txt结尾的
4 
5 print("%s---filename.endswith('doc')="%filename,res)

1 s='hello'
2 
3 res=s.startswith('he')
4 
5 print("%s---s.startswith('he')"%s,res)

1 str = "this is string example....wow!!!";
2 
3 res=str.startswith( 'is', 2, 4 )
4 
5 print ("%s---str.startswith( 'is', 2, 4 )="%str,res)
6 
7 res=str.startswith( 'this', 2, 4 )
8 
9 print  ("%s---str.startswith( 'this', 2, 4 )="%str,res)

 1 str = "this is string example....wow!!!";
 2 
 3 suffix = "wow!!!"
 4 
 5 res=str.endswith(suffix,20)
 6 
 7 print ("%s---str.endswith('wow!!!',20)="%str,res)
 8 
 9 suffix = "is"
10 
11 res=str.endswith(suffix, 2, 4)
12 
13 print ("%s---str.endswith('is', 2, 4)="%str,res)
14 
15 res=str.endswith(suffix, 2, 6)
16 
17 print ("%s---str.endswith('is', 2, 6)="%str,res)

 1 #完成文件上传的验证 只能上传图片
 2 
 3 while True:
 4 
 5     path=input('请选择文件:')
 6 
 7     p=path.rfind('\\')
 8 
 9     filename=path[p+1:]
10 
11     if filename.endswith('jpg') or filename.endswith('bmp') or filename.endswith('gif') or filename.endswith('png'):
12 
13         print('是图片允许上传')
14 
15         break
16 
17     else:
18 
19         print('不是图片,禁止上传')

1.4 isalpha(), isdigit(),join(),lstrip(),rstrip(),strip(),split(),count()方法

#isalpha() 是否是字母,如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False。

# isdigit()是否是数字,如果字符串只包含数字则返回 True 否则返回 False。

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

#lstrip() 方法用于截掉字符串左边的空格或指定字符。

#rstrip() 删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符。

# strip():方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

#split() 切割字符串

#count(args)字符串中指定args个数

1 s='abcd6'
2 
3 result=s.isalpha()
4 
5 print("%s---s.isalpha()="%s,result)#是否是字母

1 m='1235'
2 
3 result=m.isdigit()#是否是数字
4 
5 print("%s---m.isdigit()="%m,result)

 1 #循环3次,判断是否是数字 是就累加
 2 
 3 sum=0
 4 
 5 for i in range(3):
 6 
 7     num=input('请输入数字:')
 8 
 9     if num.isdigit():
10 
11         num=int(num)
12 
13         sum+=num
14 
15 print(sum)

 1 #循环4次,判断是否是数字 是就累加,步长加一,不是就打印不是数字,并且步长不增加,
 2 
 3 sum=0
 4 
 5 i=0
 6 
 7 while i<=3:
 8 
 9     num=input("请输入数字:")
10 
11     if num.isdigit():
12 
13         num=int(num)
14 
15         sum+=num
16 
17         print('第{}个数字累加成功'.format(i))
18 
19         i+=1
20 
21     else:
22 
23         print('不是数字')
24 
25 print('sum=',sum)

1 new_str='.'.join('abc')#用于将序列中的元素以指定的字符连接生成一个新的字符串。
2 
3 print("abc---'.'.join('abc')",new_str)
4 
5 list_c=['a','c','9','7']
6 
7 result=''.join(list_c)#用于将序列中的元素以指定的字符连接生成一个新的字符串。
8 
9 print("['a','c','9','7']---''.join(list_c)",result)

 1 s='   天亮   '
 2 
 3 s=s.lstrip() #去除字符串左侧的空格
 4 
 5 print(s+'q')
 6 
 7 s=s.rstrip()#去除字符串右侧的空格
 8 
 9 print(s+'y')
10 
11 s=s.strip()#去除字符串两侧的空格
12 
13 print(s+'5')

1 str = "88888888this is string example....wow!!!8888888";
2 
3 res=str.lstrip('8')#去除字符串左边的8
4 
5 print ("%s---str.lstrip('8')="%str,res)

1 random_string = 'this is pencli    '
2 
3 res=random_string.rstrip(' ilc')#去除空格ilc这几个字符不论顺序
4 
5 print("%s---random_string.rstrip(' ilc')"%random_string,res)
6 
7 res=random_string.rstrip(' cli') #去除空格ilc这几个字符不论顺序
8 
9 print("%s---random_string.rstrip(' cli)"%random_string,res)

1 # 'm/' 是尾随字符,没有找到 '.' 号的尾随字符, 'm/' 从字符串中删除
2 
3 website = 'www.runoob.com/'
4 
5 res=website.rstrip('m/.')
6 
7 print("%s\t website.rstrip('m/.')="%website,res)

1 # 移除逗号(,)、点号(.)、字母 s、q 或 w,这几个都是尾随字符
2 
3 txt = "banana,,,,,ssqqqww....."
4 
5 x = txt.rstrip(",.qsw")
6 
7 print("%s--- txt.rstrip(\",.qsw\")="%txt,x)

1 # 删除尾随字符 *
2 
3 str = "*****this is string example....wow!!!*****"
4 
5 res=str.rstrip('*')
6 
7 print ("%s---str.rstrip('*')"%str,res)

1 str = "00000003210Runoob01230000000";
2 
3 res=str.strip( '0' );  # 去除首尾字符 0
4 
5 print ("%s---str.strip( '0' )="%str,res)

1 str = "123abcrunoob321"
2 
3 res=str.strip( '12' ) # 字符序列为 12
4 
5 print ("%s---str.strip( '12' )="%str,res)

 1 #split()
 2 
 3 s='one two every go'
 4 
 5 result=s.split(' ')
 6 
 7 print("%s---s.split(' ')"%s,result)
 8 
 9 result=s.split(" ",2) #表示按照空格作为分隔符,分隔字符串2次
10 
11 print("%s---s.split(' ',2)"%s,result)

1 str = "Google#Runoob#Taobao#Facebook"
2 
3 # 第二个参数为 1,返回两个参数列表
4 
5 res=str.split("#", 1)
6 
7 print("%s---str.split(\"#\", 1)="%str,res)

1 s='no  body  see'
2 
3 result=s.count(' ')#字符串中指定空格个数
4 
5 print("%s---s.count(' ')"%s,result)

1 s='hello  liliy how are you gril'
2 
3 result=s.count('l')#字符串中指定l个数
4 
5 print("%s---s.count('l')"%s,result)

1 str = "this is string example....wow!!!";
2 
3 res=str.count('i', 4, 40)
4 
5 print("%s---str.count('i', 4, 40)="%str,res)

posted @ 2022-03-12 01:04  万溪汇海  阅读(48)  评论(0编辑  收藏  举报