[‘string methods in’, ‘python’]
6、Slicing
slicing切片,按照一定条件从列表或者元组中取出部分元素(比如特定范围、索引、分割值)
s = ’ hello ’
s = s[:]
print(s)
hello
s = ’ h
ello ’
s = s[3:8]
print(s)
hello
7、strip()
strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
s = ’ hello '.strip()
print(s)
hello
s = ‘###hello###’.strip()
print(s)
###hello###
在使用strip()方法时,默认去除空格或换行符,所以#号并没有去除。
可以给strip()方法添加指定字符,如下所示。
s = ‘###hello###’.strip(’#’)
print(s)
hello
此外当指定内容不在头尾处时,并不会被去除。
s = ’ \n \t hello\n’.strip(’\n’)
print(s)
hello
s = ‘\n \t hello\n’.strip(’\n’)
print(s)
hello
第一个\n前有个空格,所以只会去取尾部的换行符。
最后strip()方法的参数是剥离其值的所有组合,这个可以看下面这个案例。
s = ‘www.baidu.com’.strip(‘cmow.’)
print(s)
baidu
最外层的首字符和尾字符参数值将从字符串中剥离。字符从前端移除,直到到达一个不包含在字符集中的字符串字符为止。
在尾部也会发生类似的动作
8、lstrip()
移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。
s = ’ hello '.lstrip()
print(s)
hello
同样的,可以移除左侧所有包含在字符集中的字符串。
s = ‘Arthur: three!’.lstrip('Arthur: ')
print(s)
ee!
9、rstrip()
移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。
s = ’ hello '.rstrip()
print(s)
hello
10、removeprefix()
Python3.9中移除前缀的函数。
python 3.9
s = ‘Arthur: three!’.removeprefix('Arthur: ')
print(s)
three!
和strip()相比,并不会把字符集中的字符串进行逐个匹配。
11、removesuffix()
Python3.9中移除后缀的函数。
s = ‘HelloPython’.removesuffix(‘Python’)
print(s)
Hello
12、replace()
把字符串中的内容替换成指定的内容。
s = ‘string methods in python’.replace(’ ', ‘-’)
print(s)
string-methods-in-python
s = ‘string methods in python’.replace(’ ', ‘’)
print(s)
stringmethodsinpython
13、re.sub()
re是正则的表达式,sub是substitute表示替换。
re.sub则是相对复杂点的替换。
import re
s = “string methods in python”
s2 = s.replace(’ ', ‘-’)
print(s2)
string----methods-in-python
s = “string methods in python”
s2 = re.sub("\s+", “-”, s)
print(s2)
string-methods-in-python
和replace()做对比,使用re.sub()进行替换操作,确实更高级点。
14、split()
对字符串做分隔处理,最终的结果是一个列表。
s = ‘string methods in python’.split()
print(s)
[‘string’, ‘methods’, ‘in’, ‘python’]
最后
🍅 硬核资料:关注即可领取PPT模板、简历模板、行业经典书籍PDF。
🍅 技术互助:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。
🍅 面试题库:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。
g-methods-in-python
和replace()做对比,使用re.sub()进行替换操作,确实更高级点。
14、split()
对字符串做分隔处理,最终的结果是一个列表。
s = ‘string methods in python’.split()
print(s)
[‘string’, ‘methods’, ‘in’, ‘python’]
最后
🍅 硬核资料:关注即可领取PPT模板、简历模板、行业经典书籍PDF。
🍅 技术互助:技术群大佬指点迷津,你的问题可能不是问题,求资源在群里喊一声。
🍅 面试题库:由技术群里的小伙伴们共同投稿,热乎的大厂面试真题,持续更新中。
🍅 知识体系:含编程语言、算法、大数据生态圈组件(Mysql、Hive、Spark、Flink)、数据仓库、Python、前端等等。