WELCOME

不积跬步,无以至千里;不积小流,无以成江海。

Python的strip()函数

1.strip()函数

 

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

语法结构:

 

str.strip([chars])
参数

chars -- 移除字符串头尾指定的字符序列。

返回值

返回移除字符串头尾指定的字符生成的新字符串。



 

 

2.例子

 1 str = "00000003210Runoob01230000000"; 
 2 print str.strip( '0' ); # 去除首尾字符 0 
 3  
 4 str2 = " Runoob "; # 去除首尾空格 
 5 print str2.strip();
 6  
 7  
 8 # result
 9  
10 3210Runoob0123
11  
12 Runoob
1 str = "123abcrunoob321" 
2 print (str.strip( '12' )) # 字符序列为 12
3  
4  
5 # result
6  
7 3abcrunoob3
8  

 

3.lstrip()和rstrip()

 

lstrip():方法用于移除字符串头部指定的字符(默认为空格或换行符)或字符序列。
rstrip():方法用于移除字符串尾部指定的字符(默认为空格或换行符)或字符序列。
1 a = 'aaabbbbcccaaa'
2 a = a.lstrip('a')
3 print(a)
4 # >> bbbbcccaaa
5 
6 a = 'aaabbbbcccaaa'
7 a = a.rstrip('a')
8 print(a)
9 # >> aaabbbbccc

 

posted @ 2022-03-25 21:28  Ambitious~  阅读(313)  评论(0)    收藏  举报