溫馨提示×

python字符串去空格的方法是什么

小億
84
2023-12-29 20:13:19
欄目: 編程語言

Python中字符串去除空格的方法有多種,常用的方法有以下幾種:

  1. 使用strip()方法:strip()方法可以去除字符串兩端的空格。例如:
s = "   hello world   "
s = s.strip()
print(s)  # 輸出:hello world
  1. 使用lstrip()和rstrip()方法:lstrip()方法可以去除字符串左邊的空格,rstrip()方法可以去除字符串右邊的空格。例如:
s = "   hello world   "
s = s.lstrip()
print(s)  # 輸出:hello world

s = "   hello world   "
s = s.rstrip()
print(s)  # 輸出:   hello world
  1. 使用replace()方法:replace()方法可以替換字符串中的指定字符,可以將空格替換為空字符串。例如:
s = "   hello world   "
s = s.replace(" ", "")
print(s)  # 輸出:helloworld
  1. 使用正則表達式:使用re模塊中的sub()方法可以實現(xiàn)正則替換,可以使用正則表達式匹配空格并替換為空字符串。例如:
import re

s = "   hello world   "
s = re.sub(r"\s", "", s)
print(s)  # 輸出:helloworld

以上是常用的幾種方法,根據(jù)具體需求可以選擇適合的方法。

0