日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python去掉空格的一些常用方式_python

作者:清泉影月 ? 更新時間: 2022-04-09 編程語言

前言:

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

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*

eg3:join()方法+split()方法

可以去除全部空格

# join為字符字符串合成傳入一個字符串列表,split用于字符串分割可以按規(guī)則進行分割

>>> a = " a b c "
 
>>> b = a.split()  # 字符串按空格分割成列表
 
>>> b ['a', 'b', 'c']
 
>>> c = "".join(b) # 使用一個空字符串合成列表內容生成新的字符串
 
>>> c 'abc'
 
 
 
# 快捷用法
 
>>> a = " a b c "
 
>>> "".join(a.split())
 
'abc'

總結

原文鏈接:https://blog.csdn.net/qingquanyingyue/article/details/93907224

欄目分類
最近更新