字符串的内置函数

字符串常用内建函数

更多查看👉Python 的字符串内建函数

 

大小写转换

capitalize() title() upper() lower() istitle() isupper() islower()

#大小写相关
#capitalize() title() upper() lower() istitle() isupper() islower()
message='zhaorui is a beautiful girl'
print(message.capitalize())  #将第一个字符串首字母大写

print(message.title()) #将每个字符串的首字母大写

print(message.title().istitle()) #判断每个字符串的首字母是否大写

print(message.upper()) #将所有字符都大写

print(message.lower()) #将所有字符都小写

 

验证码案例

有关random模块randint()函数的介绍

有关range()函数介绍

#验证码案例
import random
s='abcdefghijklmnopqrstyvwxyzABCDEFGHIJKLMNOPQRSTYVWXYZ0123456789'
code=''
count=1
while count<=4:
    ran = random.randint(0,len(s)-1)#len长度为62需要减1,不然下标越界
    code+=s[ran] 
    count+=1
print('验证码:'+code)

#第二种写法
code=''
for i in range(4):
    ran = random.randint(0,len(s)-1)
    code += s[ran]
print('验证码:'+code)

#判断用户输入验证码
user_input = input('请输入验证码:')
if user_input.lower() == code.lower():
    print('验证码输入正确!')
else:
    print('验证码输入错误!')

 

查找相关

find() rfind() index() rindex() replace()

#字符串查找、替换相关的内建函数
#find() rfind()  index() rindex()   replace()
s1='index lucy lucky goods'
result1 ='R' in s1  #查找R是否在s1中,返回布尔
print(result1) #False

result2 = s1.find('R') #未找到返回-1
print(result2) #-1

result3= s1.find('l') #返回第一次找到的字符的索引值
print(result3) #6

result4= s1.find('l',result3+1) #从指定result3+1的位置开始从后找l并返回索引值
print(result4) #11

#find('要查找的字符',start,end)
result5= s1.find('l',result3+1,len(s1)-5) #从指定result3+1的位置到len(s1)-5的范围内找l出现的索引值
print(result5) #11

s1='this is a test of Python'
print(s1[s1.find('test'):s1.find('test')+4]) #取出test

#找图片名字
#rfind()从右侧开始找 lfind()从左侧开始找
url ='https://www.baidu.com/img/bd_logo1.png'
p = url.rfind('/')
print(url[p+1:]) #bd_logo1.png

#获取文件扩展名
p=url.find('.')
print(url[p+1:])

#index()与find类似,区别在于index找不到字符串时会报一个异常
# p = 'hello'.index('x')
# print(p) #会抛出异常

#replace(被替换字符,替换字符,替换次数)
s1 = 'index lucy lucky goods'
print(s1.replace(' ','#',2)) #将前两个空格替换为#
print(s1.replace(' ',''))

 

编码解码

encode()编码 

decode()解码
为了便于在网络上传输所以需要编码跟解码,以及使用中文也会涉及到编码。

 

#gbk中文  gb2312简体中文
msg = '上课啦!'
r1 =msg.encode('UTF-8','strict') #值为strict意为编码错误引起一个UnicodeError报错,值为ignore则忽略报错
r2 =msg.encode('GBK')
print(r1)
print(r2)
'''
out:
b'\xe4\xb8\x8a\xe8\xaf\xbe\xe5\x95\xa6\xef\xbc\x81'
b'\xc9\xcf\xbf\xce\xc0\xb2\xa3\xa1'
'''

 

 

开头和结尾

 startswith跟endswith

'''
字符串内建函数
startswith()  endswith() 返回值都为布尔类型
判断是否以xxx开头
判断是否以xxx结尾
主要应用于判断上传的文件格式
'''
filename= '笔记.doc'
result=filename.endswith('txt') #filename是否以txt结尾的
str1='hello'
result=str1.startswith('H')
print(result)

 

是否由字母数字组成

 isalpha()跟isdigit()

'''
isalpha()
判断字符串是否只由字母组成
isdigit()
判断字符串只由数字组成
'''
str1='abcd'
print(str1.isalpha())

#小游戏,累加数字
sum=0
for i in range(3):
    num=input('请输入数字:')
    if num.isdigit():
        sum+=int(num)
    else:
        print('你输入的不是数字!')
print('你输入的数字总和为:',sum)

#小游戏升级版,必须输入3次
sum=0
i=1
while i<=3:
    num = input('请输入数字:')
    if num.isdigit():
        sum+=int(num)
        i+=1
    else:
        print('你输入的不是数字!请重新输入!')
print('你输入的3次数字的总和为:',sum)

 

连接相关

join()

'''
join()
以指定字符串作为分隔符,将seq(序列)中所有元素合并成新的字符串
'''
new_str='-'.join('abc')
print(new_str) #输出a-b-c

list1 = ['a','b','c']
new_str =''.join(list1)
print(new_str) #输出abc

 

去除空格

strip()

'''
lstrip()截掉字符串左边的空格或指定字符
同理rstrip()去除右侧的空格
strip()同时去除字符串两边的空格
'''
s='  hello  '
print(s.lstrip()+'8') #输出hello  8

split()

'''
split()分割字符串,并放入列表中
count()求指定字符串的个数
'''
s = 'hello world is kitty'
print(s.split(' ')) #输出['hello', 'world', 'is', 'kitty']
print(s.count(' '))#输出3,表示有3个空格
print(s.split(' ',2)) #输出['hello', 'world', 'is kitty']

 

学习来自:B站大学 P42-47

菜鸟教程

posted @ 2020-11-08 16:04  努力吧阿团  阅读(195)  评论(0编辑  收藏  举报