文章目录
split才是切割…
而不是strip…,今天居然用错了…
在某种情况下,split切割出来的结果会比预期的长度多1…
下面举例子:
a='32123-32123-123-32123-23'
b=a.split('23')
print(b)
print(b[-1])
if b[-1]=='':
b.pop()
print(b)
输出:
['321', '-321', '-1', '-321', '-', '']
['321', '-321', '-1', '-321', '-']
这样的情况下,输出才是想要的结果:
c='www.baidu.com'
d=c.split('.')
print(d)
# 输出
['www', 'baidu', 'com']
值得注意的是,split只能切割字符串…不能切割列表,但是切割字符串出来的结果却是列表…
是不是很神奇…
e=[1,2,3]
f=e.split(',')
print(f)
AttributeError: 'list' object has no attribute 'split'
错误信息:
AttributeError: 'list' object has no attribute 'split'
join的使用
join()函数
对字符串的操作
c = '1234'
d = 'abc'
e = c.join(d)
print(e) # a 1234b1234c
对列表的操作
f = ['a','b','c']
g = ":".join(f)
print(g) # a:b:c
当列表元素为int类型的时候:会报错
h =[1,2,3,4]
l = "".join(h)
print(l)
TypeError: sequence item 0: expected str instance, int found
对字典的操作
结果为将其所有的键以join前面的符号进行了连接
p = {'1':'c','2':'d','3':'e'}
o = ":".join(p)
print(o) # 1:2:3
对元祖的操作
和列表一样,元祖内容为int类型的时候,也会报错
q = (1,2,3,4,6,3,2)
e = ":".join(q)
print(e) # TypeError: sequence item 0: expected str instance, int found
当内容为str类型的时候,就正常了
q = ('1','2','4','3')
e = ':'.join(q)
print(e) # 1:2:4:3
os.path.join()函数
将括号里的路径,组合后进行返回
import os
print(os.path.join('E:\py_test','test.py'))
# E:\py_test\test.py