# 示例代码:去除字符串中的空格
# 方法1:使用 replace() 方法去除所有空格
def remove_all_spaces(s):
return s.replace(" ", "")
# 解释:replace(" ", "") 会将字符串中的所有空格替换为空字符,从而达到去除空格的效果。
# 方法2:使用 join() 和 split() 方法去除所有空格
def remove_all_spaces_split_join(s):
return "".join(s.split())
# 解释:split() 方法默认按空格分割字符串并返回一个列表,join() 方法再将列表中的元素连接成一个新的字符串,从而去除所有空格。
# 方法3:使用正则表达式去除所有空格
import re
def remove_all_spaces_regex(s):
return re.sub(r"\s+", "", s)
# 解释:re.sub(r"\s+", "", s) 使用正则表达式 \s+ 匹配一个或多个空白字符(包括空格、制表符等),并将它们替换为空字符。
# 示例
input_string = " Hello World "
print(remove_all_spaces(input_string)) # 输出: HelloWorld
print(remove_all_spaces_split_join(input_string)) # 输出: HelloWorld
print(remove_all_spaces_regex(input_string)) # 输出: HelloWorld
上一篇:python创建空集合
下一篇:python删除字符串末尾的字符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站