首頁  >  文章  >  後端開發  >  Python如何刪除字串中所有空格

Python如何刪除字串中所有空格

青灯夜游
青灯夜游原創
2019-01-19 14:53:5626179瀏覽

在Python中刪除字串中所有空格有:使用replace()函數、使用split()函數 join()函數、使用Python正規表示式。以下這篇文章就來具體介紹一下這些方法,希望對大家有幫助。 【相關影片教學推薦:Python教學

Python如何刪除字串中所有空格

#使用replace()函數

Python如何刪除字串中所有空格

#我們可以使用replace()函數,把所有的空格(" ")替換為("")

def remove(string): 
    return string.replace(" ", "");
    
string = ' H  E  L  L  O  ! ';
print("原字符串:"+string) ;
print("\n新字符串:"+remove(string)) ;

輸出:

Python如何刪除字串中所有空格

使用split()函數join()函數
split()函數會透過指定分隔符號對字串進行切片,傳回分割後的字串的所有單字元列表。然後,我們使用join()函數迭代連接這些字元。

def remove(string): 
     return "".join(string.split());

string = 'w  o  r  l  d ';
print("原字符串:"+string) ;
print("\n新字符串:"+remove(string)) ;

輸出:

Python如何刪除字串中所有空格#使用Python正規表示式

################################################################################### Python 自1.5版本起增加了re 模組,它提供Perl 風格的正規表示式模式。 ######re 模組讓 Python 語言擁有全部的正規表示式功能。 ###
#导入re 模块
import re
def remove(string): 
    pattern = re.compile(r'\s+');
    return re.sub(pattern,'', string);

string = 'P  y  t  h  o  n';
print("原字符串:"+string);
print("\n新字符串:"+remove(string)) ;
###輸出:###############以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。更多精彩內容大家可以追蹤php中文網相關教學欄位! ! ! ###

以上是Python如何刪除字串中所有空格的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn