Python去除字串前後空格的幾種方法

2021-09-10 19:57:11 字數 1141 閱讀 9083

其實如果要去除字串前後的空格很簡單,那就是用strip(),簡單方便

>>> ' a bc  '.strip()

'a bc'

如果不允許用strip()的方法,也是可以用正則匹配的方法來處理。

>>> s1 = ' a bc'

>>> s2 = 'a bc '

>>> s3 = ' a bc '

>>> s4 = 'a bc'

>>> def trim(s):

... import re

... if s.startswith(' ') or s.endswith(' '):

... return re.sub(r"^(\s+)|(\s+)$", "", s)

... return s

>>> trim(s1)

'a bc'

>>> trim(s2)

'a bc'

>>> trim(s3)

'a bc'

>>> trim(s4)

'a bc'

如果也不用正則匹配的話,還可以借助遞迴函式來去除前後的空格。

>>> s1 = ' a bc'

>>> s2 = 'a bc '

>>> s3 = ' a bc '

>>> s4 = 'a bc'

>>> def trim(s):

... if s[0] == " ":

... return trim(s[1:]) # 如果開首有多個空格的話,遞迴去除多個空格

... elif s[-1] == " ":

... return trim(s[:-1]) # 如果末尾有多個空格的話,遞迴去除多個空格

... else:

... return s

>>> trim(s1)

'a bc'

>>> trim(s2)

'a bc'

>>> trim(s3)

'a bc'

>>> trim(s4)

'a bc'

js去除字串空格

方法一 使用replace正則匹配的方法 去除所有空格 str str.replace s g,去除兩頭空格 str str.replace s s g,去除左空格 str str.replace s 去除右空格 str str.replace s g,str為要去除空格的字串,例項如下 var s...

js去除字串空格?

方法一 使用replace正則匹配的方法 去除所有空格 str str.replace s g,去除兩頭空格 str str.replace s s g,去除左空格 str str.replace s 去除右空格 str str.replace s g,str為要去除空格的字串,例項如下 var s...

去除字串中間空格

經常會遇到這樣的問題 使用ssm框架或者其他框架的時候,存入到資料庫之前會將資料去除空格然後再存入,不然的話顯示的時候或者在儲存的時候會有問題。做法 如果是單純的去除前後空格的話,可以使用trim 函式,但是中間空格是不可以去除的,有沒有什麼做法可以將中間的空格也去除呢?答案是可以 使用正規表示式 ...