python中去掉字符串中的空格

我們想去除字符串中不必要的空格時可以使用如下方法:

在這裏以str作爲例子來演示。在str中前中後三處都有空格。

函數原型:

聲明:str爲字符串,rm爲要刪除的字符序列

  • str.strip(rm) : 刪除s字符串中開頭、結尾處,位於 rm刪除序列的字符

  • str.lstrip(rm) : 刪除s字符串中開頭(左邊)處,位於 rm刪除序列的字符

  • str.rstrip(rm) : 刪除s字符串中結尾(右邊)處,位於 rm刪除序列的字符

  • str.replace(‘s1’,’s2’) : 把字符串裏的s1替換成s2。故可以用replace(’ ‘,”)來去掉字符串裏的所有空格

  • str.split() : 通過指定分隔符對字符串進行切分,切分爲列表的形式。

  • 去除兩邊空格:

>>> str = ' hello world '
>>> str.strip()
'hello world'
  • 去除開頭空格:
>>> str.lstrip()
'hello world '
  • 去除結尾空格:
>>> str.rstrip()
' hello world'
  • 去除全部空格:
>>> str.replace(' ','')
'helloworld'
  • 將字符串以空格分開:
>>> str.split()
['hello', 'world']
>>> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章