字符串常用属性和方法:
1.获取字符串长度
len( )函数: 获取字符串的长度
s =‘Python’
print(len(s)) # 6
2. 查找内容
find( ) 函数: 查找指定内容在字符串中是否存在,若存在则返回该内容在字符串中第一次出现的位置索引,不存在返回-1
s =‘This is a test OK, OK Or NOT’
print(s.find(‘OK’))
输出:15
print(s.find(‘OK’, 17))
输出: 19
print(s.find(‘PASS’))
输出:-1 (不存在,则返回-1)
3.判断字符串的开头和结尾
startswith(), endswith(): 判断字符串是否以某字符串开头或结尾
测试代码:
s =‘This is a test OK, OK Or NOT’
print(s.startswith(‘This’))
print(s.startswith(‘THIS’))
print(s.endswith(‘NOT’))
print(s.endswith(‘Not’))
输出:
True
False
True
False
4. 计算出现的次数
count()函数:计算某字符串在在字符串中出现的次数
测试代码:
s =‘AAAaaaBbbbCccc’
print(s.count(‘A’))
print(s.count(‘C’))
输出:
3
1
5.替换内容
replace( )函数:替换字符串中指定的内容,如果指定次数,则替换不超过指定次数
测试代码:
s =‘AAAaaaBbbbCccc’
print(s.replace(‘a’, ‘A’))
输出:
AAAAAABbbbCccc
print(s.replace(‘c’,‘A’))
输出:
AAAaaaBbbbCAAA
6. 切割字符串
split( )函数:通过参数的内容分隔字符串
测试代码:
s =‘1#3#5#8’
print(s.split(’#’))
输出:
[‘1’, ‘3’, ‘5’, ‘8’]
7.修改大小写
upper(),lower( )函数:字符串大小写转换
测试代码:
s =‘test’
print(s.upper())
print(s.lower())
输出:
TEST
test
8.空格处理
strip()函数: 去空格
测试代码:
s =’ space character strip ’
print(’|’, s, ‘|’)
print(’|’, s.lstrip(), ‘|’)
print(’|’, s.rstrip(), ‘|’)
print(’|’, s.strip(), ‘|’)
输出:
| space character strip |
| space character strip |
| space character strip |
| space character strip |
lstrip函数去掉左边空格,l表示left, r表示right,当然是去掉右边空格,什么也不加的情况是去掉左右的空格。
9.字符串拼接
join() 函数:字符串拼接
测试代码:
s =’$’
print(s.join(‘Python’))
输出:
P y y yt h h ho$n
将字符插入搭配字符串的每个字符直接