新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python字符串去空格的有哪些方法,Python字符串去空格

发布时间:2023-12-29 20:13:19

python字符串去空格的有哪些方法

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()方法可以实现正则替换,可使用正则表达式匹配空格并替换为空字符串。例如:
import re

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

以上是经常使用的几种方法,根据具体需求可以选择合适的方法。