去掉字符空格的方法


處理字符串時經常要定制化去掉無用的空格,python 中要么用存在的常規方法,或者用正則處理

1.去掉左邊空格
string = " * it is blank space test * "
print (string.lstrip())

result:
* it is blank space test *

2.去掉右邊空格
string = " * it is blank space test * "
print (string.rstrip())

result:
* it is blank space test *

3.去掉左右兩邊空格
string = " * it is blank space test * "
print (string.strip())

result:
* it is blank space test *

4.去掉所有空格
有兩種方式
eg1:調用字符串的替換方法把空格替換成空

string = " * it is blank space test * "
str_new = string.replace(" ", "")
print str_new

result:
*itisblankspacetest*
eg2:正則匹配把空格替換成空

import re

string = " * it is blank space test * "
str_new = re.sub(r"\s+", "", string)
print str_new

result:
*itisblankspacetest*

 

來源: https://blog.csdn.net/qingquanyingyue/article/details/93907224

 

https://i-beta.cnblogs.com/posts/edit-done;postId=12681418


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM