有以下几种方法可以去除字符串中的空格:
使用replace()方法:使用空字符串替换字符串中的空格。string = "hello world"string = string.replace(" ", "")print(string) # 输出"helloworld"使用split()和join()方法:先使用split()方法将字符串分割成列表,再使用join()方法将列表中的元素拼接成一个新的字符串,空格会被忽略。string = "hello world"string = "".join(string.split())print(string) # 输出"helloworld"使用正则表达式:使用re模块中的sub()函数,将匹配到的空格替换为空字符串。import restring = "hello world"string = re.sub(r"\s", "", string)print(string) # 输出"helloworld"这些方法都可以去除字符串中的空格,选择哪种方法取决于具体的需求和使用场景。

