Python 字符串常用方法 day2

2022-12-07,,,,

1、去空格和换行符:

s = '  a   bc   '
print(s.strip())#strip(),去掉字符串两边的空格和换行符,无法去除中间的空格
print(s.rstrip())#rstrip(),去掉右边的空格
print(s.lstrip())#lstrip(),去掉左边的空格

2、替换:

print(s.replace('a','A')) #把a替换为A,返回一个新的字符串,只替换不会更改原字符串
print(s.replace(' ',''))#把空格替换为空字符串

3、找下标:

s = 'abc'
print(s.index('c')) #找下标
print(s.find('a')) #找下标,若元素存在则同index
print(s.find('e')) #找不存在的下标,返回-1,用find
# print(s.index('f'))#找不存在的下标,报错ValueError

4、大小写

print(s.upper()) #把所有字母都变为大写
print(s.lower()) #把所有字母都变为小写
print(s.capitalize())#首字母大写,其余小写
print(s.title())#标题化,所有单词的首字母大写

5、补齐

print(s.center(50,'='))#把原字符串放在中间,若不够50,则将补齐50
print(s.center(5,'*'))

6、统计次数

print(s.count('c')) #找某个字符出现的次数

7、补零

s2 = ''
print(s2.zfill(5)) #在前面补0,补5-1个0

8、各种判断 

print(s.startswith('a'))#true ,判断是否已xx开头
print(s.endswith('.jpg'))#false,判断是否已xx结尾
print(s.isdigit())#判断字符串里存的是否为整数
print(s2.islower())#是不是全是小写字母 ,数字应都是false
print(s2.isupper())#是不是全是大写字母
print(s2.isalpha())#是字母或汉字,全都返回true
print(s2.isalnum())#只有数字或字母或汉字会返回true,其他的全返回false(用于不允许输入特殊字符的情况)
print(s2.isspace())#判断是否都是空格

9、字符串格式化

s3 = '今天是{},欢迎{}登录'
s4 = 'insert into stu (id,username,passwd,phone) value ("{id}","{username}","{password}","{phone}")' print(s3.format('','小明')) #做字符串格式化的
print(s4.format(username = 'abc',id = 1,password = 'abc12323',qq = '',phone = ''))
print(s4.format_map({"username":"abc",'id':1,"password":"dfasdf","phone":''}))#传一个字典

10、分割字符串(常用

stus='xiaoming,xiaohei,xiaobai,jaojun'
print(stus.split(',')) #分割字符串,常用!!! 以逗号分割
example = 'a b c d ef 123'
print(example.split())#什么都不写,则以空格分割
print(example.split('.'))#没有句号 则将字符串放到一个list里

11、连接字符串(常用)

l = ['xiaoming', 'xiaohei', 'xiaobai', 'jaojun']

print(','.join(l)) #把list里面的每一个元素通过指定的字符串连接起来
print(' '.join(l)) #用空格把元素连接起来

Python 字符串常用方法 day2的相关教程结束。

《Python 字符串常用方法 day2.doc》

下载本文的Word格式文档,以方便收藏与打印。