学堂 学堂 学堂公众号手机端

python去除空格的方法有哪些

lewis 3年前 (2023-01-26) 阅读数 5 #技术

  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"

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门