Python去掉字串中的空格方法總結

2021-10-05 04:04:09 字數 899 閱讀 7522

大腦的總結,很全面

python中常見字串去除空格的方法總結

1:strip()方法,去除字串開頭或者結尾的空格

>>> a = " a b c "

>>> a.strip()

'a b c'

2:lstrip()方法,去除字串開頭的空格

>>> a = " a b c "

>>> a.lstrip()

'a b c '

3:rstrip()方法,去除字串結尾的空格

>>> a = " a b c "

>>> a.rstrip()

' a b c'

4:replace()方法,可以去除全部空格

#replace主要用於字串的替換replace(old, new, count)

>>> a = " a b c "

>>> a.replace(" ", "")

'abc'

5: join()方法+split()方法,可以去除全部空格

#join為字元字串合成傳入乙個字串列表,split用於字串分割可以按規則進行分割

>>> a = " a b c "

>>> b = a.split() # 字串按空格分割成列表

>>> b ['a', 'b', 'c']

>>> c = "".join(b) # 使用乙個空字串合成列表內容生成新的字串

>>> c 'abc'

# 快捷用法

>>> a = " a b c "

>>> "".join(a.split())

'abc'

關於Python去掉字串中的空格

經常會遇到需要將字串中的空格去掉的情況,通常我們有三種解決方法 1 strip char 方法 該方法是不能將字串中間的空格去掉的!a wode ge niu a.strip wode ge niu a wode ge niu a.lstrip wode ge niu a wode ge niu a...

python中去掉字串中的空格

我們想去除字串中不必要的空格時可以使用如下方法 在這裡以str作為例子來演示。在str中前中後三處都有空格。函式原型 宣告 str為字串,rm為要刪除的字串行 str.strip rm 刪除s字串中開頭 結尾處,位於 rm刪除序列的字元 str.lstrip rm 刪除s字串中開頭 左邊 處,位於 ...

QString去掉字串中的空格

qstring中去掉多餘空格的方法有三種 1.remove方法來實現 qstring str aa ss ff jj str.remove qregexp s 這種方式會去掉字串中的所有空格。結果 aassffjj 2.simplified qstring str aa t ss n ff r n ...