字符串常用功能:
*移除空白
*分割
*长度
*索引
*切片
方法:
1.切片(
[开始:结束]:默认值为序列的开始和结束
索引值是指到要在那里“切下”
)
>>> S[0],S[-2]
('s', 'a')
>>> S = 'spam'
>>> S[0],S[-2] #索引
('s', 'a')
>>> S[1:3],S[1:],S[:-1] #分片
('pa', 'pam', 'spa')
分片运作原理:
S[i:j]
——提取S的一部分作为一个序列。
——上边解并不包含在内,j为上边界,i为下边界
——分片的边界默认为0和序列的长度(如果没有明确给出)
——S[1:3] 获取从偏移为1的元素,直到但不包括偏移为3的元素
——S[1:] 获取从偏移为1的元素直到末尾(偏移序列长度)元素
——S[:3] 获取从偏移为0的元素直到但不包括偏移为3的元素
——S[:-1] 获取从偏移为0的元素直到但不包括最后一个元素之间的元素
——S[:] 获取从偏移为0的元素直到末尾的元素,实现了S的拷贝
2.字符串转换:
不能让字符串和数字相加,
>>> '42'+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> int('42')+1
43
>>> '42'+str(1)
'421'
二,字符串方法:
1.strip,lstrip,rstrip
strip(去除带有相应字符)
S = 'saaaay yes no yaaaaaasss'
>>> S.strip('say')
' yes no '
lstrip,rstrip(当没有参数传入时,默认去除首尾空格)2.修改字符串
用切片来加索引来修改字符串
S = 'spammy'
>>> S = S[:3]+'xx'+S[-1] #使用分片加索引来修改字符串
>>> S
使用 str 内置函数来
1首字母大写test.capitalize()
test = "aLex"
首字母大写
v = test.capitalize()
print(v)
2.所有变小写test.casefold()
v1 = test.casefold()
print(v1)
v2 = test.lower()
print(v2)
3.设置宽度,并将内容居中test.center()
# * 空白未知填充,一个字符,可有可无
# v = test.center(20,"中")
# print(v)
4.在字符串中寻找,子序列的出现次数test.count()
test = "aLexalexr"
v = test.count('ex')
print(v)
test = "aLexalexr"
v = test.count('ex',5,6)
print(v)
5.字符串中是否只包含字母或数字test.isalnum()
test = "123"
v = test.isalnum()
print(v)
6.index找不到,报错
test = "alexalex"
v = test.index('8')
print(v)
7.find,找不到返回-1
test = "alexalex"
v = test.index('8')
print(v)
8.是否是字母,汉字 text.isalpha()
test = "as2df"
v = test.isalpha()
print(v)
9.判断输入是否是数字 isdecimal() isdigit() isnumeric()
test = "二" # 1,②
v1 = test.isdecimal()
v2 = test.isdigit()
v3 = test.isnumeric()
print(v1,v2,v3)
10.是否存在不可显示字符 ispriinttable()
\t 制表符
\n 换行
test = "oiuas\tdfkj"
v = test.isprintable()
print(v)
11.判断是否全部是空格 isspace()
test = ""
v = test.isspace()
print(v)
12.将字符串中每个元素按招指定分隔符连接 join()
# test = "你是风儿我是沙"
# print(test)
# # t = ' '
# v = "_".join(test)
# print(v)
13.对应关系替换 maketrans()
v = "asidufkasd;fiuadkf;adfkjalsdjf"
# m = str.maketrans("aeiou", "12345")
# new_v = v.translate(m)
# print(new_v)
14.分割字符串 rartition() partition()
# test = "testasdsddfg"
# v = test.partition('s')
# print(v)
# v = test.rpartition('s')
# print(v)
15.分割为指定个数 rsplit()
# v = test.split('s',2)
# print(v)
# test.rsplit()
16.大小写转换 swapcase()
# test = "aLex"
# v = test.swapcase()
# print(v)