python——strip与split的区别

有时候总是分不清split跟strip,也有人问我去掉空格到底是用strip啊还是split啊,现在就来探讨一下什么时候用strip,什么时候用split

strip()函数

用法:(1)用于移除字符串头尾指定的字符(默认为空格)。
就比如这个例子,strip()就默认将string2里面的字符串的空格去掉,输出结果为:abc

string2 = '  abc'
print(string2.strip())

(2)strip()还可以去掉指定的字符,在strip(‘要去掉的字符’)在括号里输入要去掉的字符,但是strip只能删除前后指定的字符,遇到空格就会不理

string = 'hello thank you are you ok hello'
result = string.strip('helo')
print(result)

输出结果为: thank you are you ok

(3)比如说有时候爬取网页的时候会碰到一对的\n,\t什么的,也可以用strip把它们去掉

string = 'fhau\nweifh\nfhow\niaehf\tfweioaufh\n'
result = string.strip('\n\t')
print(result)

输出结果为:
fhau
weifh
fhow
iaehf fweioaufh

split()函数

split()一般用于拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串弄成列表,也就是list,list应该知道吧?比如这种[‘a’,‘b’,‘c’]就是列表

(1)下面这个例子是以**.**来切割字符串,简单来说就是把小点两边的分离

string3 = 'www.baidu.com'
result = string3.split('.')
print(result)

输出结果为:[‘www’, ‘baidu’, ‘com’]

(2)分离个数,可以在split(’.’,个数),个输入为(int)整数

string3 = 'www.baidu.com'
result = string3.split('.',1)
print(result)

输出结果为:[‘www’, ‘baidu.com’],很多人会好奇为什么不是输出一个元素,而是输出两个元素,其实这里的1是从零开始数的,跟数组差不多,所以打印的结果是两个元素

(3)取列表元素的序列

string3 = 'www.baidu.com'
result = string3.split('.',1)[0]
print(result)

输出结果为:www,这个应该不难理解,[0]就是取第一个元素,[1]就是取第二个元素

(4)分开打印,这里可以将两个值分别赋给两个变量,是不是觉得python的优点了呢?

string3 = 'www.baidu.com'
result,re = string3.split('.',1)
print(result+"\n",re)

输出结果为:
www
baidu.com

(5)相信喜欢爬虫的朋友们都遇到过爬取网页是爬到很多无关的符号啊,标签吧,用split可以轻松解决,个人觉得正则表达式效果更好

string3 = '<html><body>[Hello World]</body></html>'
result = string3.split("[")[1].split("]")[0]
print(result)

输出结果为:Hello World

正在尝试写博客,把会的分享给你们,如有写的不好的地方,希望指点一下,喜欢的朋友们请点个赞,谢谢!

猜你喜欢

转载自blog.csdn.net/Woo_home/article/details/88588197