python去除空格的方法有哪些

1544
2024/3/4 21:01:09
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

  1. 使用strip()方法去除字符串两端的空格:
s = "  hello world  "
print(s.strip())
# Output: "hello world"
  1. 使用replace()方法替换空格:
s = "  hello world  "
print(s.replace(" ", ""))
# Output: "helloworld"
  1. 使用join()方法和split()方法去除所有空格:
s = "  hello world  "
print("".join(s.split()))
# Output: "helloworld"
  1. 使用正则表达式re.sub()去除所有空格:
import re
s = "  hello world  "
print(re.sub(r"\s+", "", s))
# Output: "helloworld"

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实现