- 学习测试开发的Day84,真棒!
- 学习时间为1H25M
- 第八次全天课(下午视频2H11M-3H15M)
>>> "Abc".index("a",0,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> "Abc".index("b",0,2)
1
>>>
rfind
>>> "abcabc".rfind("c")
5
>>> "abcabc".find("c")
2
>>> "abcabc".rfind("c",0,5)
2
>>> "abcabc".rfind("c",0,6)
5
>>>
rindex()
replace()
>>> "abcabc".replace("ab","**")
'**c**c'
>>> "abcabc".replace("ab","**",1)
'**cabc'
>>>
>>> "a\tb\tc".expandtabs()
'a b c'
>>> len("a\tb\tc".expandtabs())
17
>>> len("a\tb\tc".expandtabs(4))
9
>>>
字符串的分割
>>> "ab cd \nde".split()
['ab', 'cd', 'de']
>>>
>>> "a*c*d \nde".split("*",1)
['a', 'c*d \nde']
>>> "a*c*d \nde".split("*")
['a', 'c', 'd \nde']
>>>
>>> "a*b*c".split("*",1)
['a', 'b*c']
>>> "a*b*c".rsplit("*",1)
['a*b', 'c']
splitlines
>>> "a\nb\nc".splitlines()
['a', 'b', 'c']
## 按行切,1是开关,2也可以,换行符是否保留
>>> "a\nb\nc".splitlines(1)
['a\n', 'b\n', 'c']
>>>
join
>>> "*".join(["a","b"])
'a*b'
>>> "".join(["a","b"])
'ab'
>>> "_".join(["a","b"])
'a_b'
>>>
>>> "a\r\n\t\f b c".split()
['a', 'b', 'c']
>>>
join里面必须是字符串
>>> "*".join([1,2,3,4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
## map逐一遍历
>>> "*".join(map(str,[1,2,3,4]))
'1*2*3*4'
>>>
常用的字符串的测试
>>> "abc".startswith("ab")
True
>>> "abc".endswith("ab")
False
>>> "abc".endswith("bc")
True
>>> "b" in "abc"
True
>>>
>>>
常用的字符串的测试
isalpha()、isalnum()
isdigit()、isspace()
islower() 、 isupper()
istitle()
>>> "Tx De".istitle()
True
>>>
常用的字符串的映射-maketrans()
## 批量转换
>>> s='2342423423'
>>> print(s.translate(map))
bc4b4bc4bc
>>>
删除
>>> t=bytes.maketrans(b'abc',b'ABC')
>>> print(b'abc123'.translate(t,b"123"))
b'ABC'
>>>
可以删除多个
>>> t=bytes.maketrans(b'abc',b'ABC')
>>> print(b'abc12234sfdsfsdf3'.translate(t,b"123"))
b'ABC4sfdsfsdf'
>>>
常用的字符串的解码和编码-encode()
base64
传输的时候用,url不可见的字符要转成base64
http url 传输
>>> import base64
>>> encodestr=base64.b64encode(b'I love you')
>>> print(encodestr)
b'SSBsb3ZlIHlvdQ=='
>>> print(base64.b64decode(encodestr))
b'I love you'
>>>
判断类型-isinstance
python3中的ord、chr
>>> ord("z")
122
>>> ord("我")
25105
>>> chr(25105)
'我'
>>> chr(21000)
'刈'
>>> chr(31000)
'礘'
>>> chr(2000)
'\u07d0'
>>> chr(20000)
'丠'
>>>
字符串出现的次数统计
>>> "abcacb".count("a")
2
>>> "abcacb".count("ab")
1
>>> "abcacb".count("abc")
1
>>> "abcacb".count("abc",1)
0
>>> "abcacb".count("a",1,8)
1
>>> "abcacb".count("a",1,3)
0
>>> "abcacb".count("a",1,6)
1
>>> "abcacb".count("a",1,4)
1
>>> "abcbc".count("a",1,4)
0
>>> "abcabc".count("a",1,4)
1
>>> "abcabc".count("a",0,4)
2
>>>
练习1:将所有的字符串内容中的字母均替换成大写
def upper(s):
if not isinstance(s,str):
return s
result=""
for i in s:
if (i>="a" and i<="z"):
result+=chr(ord(i)-32)
else:
result+=i
return result
print(upper("我们123abcDEF"))
输出:
PS D:\0grory\day8> python .\myupper.py
我们123ABCDEF
PS D:\0grory\day8>