要删除字符串中的空格,可以使用以下方法之一:

  1. 使用replace()函数将空格替换为空字符:
string = "hello world"
new_string = string.replace(" ", "")
print(new_string)  # 输出: helloworld
  1. 使用join()函数将字符串拼接起来,并且在拼接的过程中跳过空格:
string = "hello world"
new_string = "".join(string.split())
print(new_string)  # 输出: helloworld
  1. 使用正则表达式re.sub()函数将空格替换为空字符:
import re
string = "hello world"
new_string = re.sub(r"\s", "", string)
print(new_string)  # 输出: helloworld
字符串删除空格

原文地址: https://www.cveoy.top/t/topic/hYK8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录