Python中去除字符串中空格的函数
发布时间:2023-11-29 07:03:58
Python中去除字符串中空格的函数有很多种实现方式,下面介绍几种常见的方式:
1、使用replace()方法替换空格为指定字符或空字符串:
def remove_whitespace1(string):
return string.replace(" ", "") # 替换为空字符串
使用示例:
string = "Hello World" result = remove_whitespace1(string) print(result) # HelloWorld
2、使用split()方法分割字符串后,再使用join()方法拼接字符串:
def remove_whitespace2(string):
return "".join(string.split()) # 拼接时指定分隔符为空字符串
使用示例:
string = "Hello World" result = remove_whitespace2(string) print(result) # HelloWorld
3、使用正则表达式re.sub()方法替换空格为指定字符或空字符串:
import re
def remove_whitespace3(string):
return re.sub(r"\s+", "", string) # 替换为空字符串
使用示例:
string = "Hello World" result = remove_whitespace3(string) print(result) # HelloWorld
4、使用列表推导式和join()方法去除空格:
def remove_whitespace4(string):
return "".join([char for char in string if char != " "])
使用示例:
string = "Hello World" result = remove_whitespace4(string) print(result) # HelloWorld
5、使用字符串的translate()方法去除空格:
def remove_whitespace5(string):
return string.translate(str.maketrans("", "", " "))
使用示例:
string = "Hello World" result = remove_whitespace5(string) print(result) # HelloWorld
这些函数都可以用来去除字符串中的空格,并得到去除空格后的新字符串。
