用了很久python在看别人写的程序时,以前经常一看到字符连接、去空格、字符转列表就看不懂,所以写下来
1、join用法:按照自定义方法连接列表为字符串
l = [‘a‘,‘a‘,‘a‘,‘a‘]
L1 = ‘‘.join(l) #output is ‘aaaa‘
L2 = ‘b‘.join(l) #output is ‘abababa‘
L3 = ‘5‘.join(l) # output is ‘a5a5a5a‘
2、split用法:将字符串按自定义方式切割成列表(接例1还原)
L2.split(‘b‘) #result is [‘a‘, ‘a‘, ‘a‘, ‘a‘]
L3.split(‘5‘) #result is [‘a‘, ‘a‘, ‘a‘, ‘a‘]
3、strip用法:取掉字符两端字符(默认是空格,当然也可以以自定义字符放到括弧里),所以就有rstrip(),lstrip(),意思是去掉右边、去掉左边
l = ‘222hello22222222‘
l.strip(‘2‘) #output is ‘hello‘
l.rstrip(‘2‘) # output is 222hello
l.lstrip(‘2‘) #output is hello2222222
时间: 2024-12-25 17:26:12