租用问题

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

< 返回租用问题列表

string去空格的有什么方法,string去掉

发布时间:2023-10-17 04:50:24

string去空格的有甚么方法

有以下几种方法可以去除字符串中的空格:

  1. 使用replace()方法:使用空字符串替换字符串中的空格。
string = "hello world"
string = string.replace(" ", "")
print(string)  # 输出"helloworld"
  1. 使用split()和join()方法:先使用split()方法将字符串分割成列表,再使用join()方法将列表中的元素拼接成一个新的字符串,空格会被疏忽。
string = "hello world"
string = "".join(string.split())
print(string)  # 输出"helloworld"
  1. 使用正则表达式:使用re模块中的sub()函数,将匹配到的空格替换为空字符串。
import re
string = "hello world"
string = re.sub(r"s", "", string)
print(string)  # 输出"helloworld"

这些方法都可以去除字符串中的空格,选择哪一种方法取决于具体的需求和使用处景。