您的位置:首页 >Python删除空白的函数写法
发布于2025-12-12 阅读(0)
扫一扫,手机访问
使用strip()删除两端空白:def remove_spaces_both_sides(text): return text.strip();2. lstrip()删左侧空白;3. rstrip()删右侧空白;4. replace()或re.sub(r"\s+", "")删所有空白字符,可封装函数复用。

在Python中,删除字符串中的空白可以使用内置的字符串方法,而不是自定义函数。但你可以将这些方法封装在函数中,方便重复调用。以下是几种常见的删除空白的方式及对应的函数写法。
使用 strip() 方法可以去除字符串开头和结尾的空白字符。
def remove_spaces_both_sides(text): return text.strip()s = " hello world " print(remove_spaces_both_sides(s)) # 输出: "hello world"
使用 lstrip() 去除字符串左侧的空白。
def remove_left_space(text): return text.lstrip()s = " hello world " print(remove_left_space(s)) # 输出: "hello world "
使用 rstrip() 去除字符串右侧的空白。
def remove_right_space(text): return text.rstrip()s = " hello world " print(remove_right_space(s)) # 输出: " hello world"
如果想删除字符串中所有的空白字符(空格、制表符、换行等),可以用 replace() 或 re.sub()。
def remove_all_spaces(text): return text.replace(" ", "")s = "hello world python" print(remove_all_spaces(s)) # 输出: "helloworldpython"
若还包括制表符、换行符等,可用正则:
import redef remove_all_whitespace(text): return re.sub(r"\s+", "", text)
s = " hello \t\n world " print(remove_all_whitespace(s)) # 输出: "helloworld"
基本上就这些常用方式。根据你要删除的空白位置和范围选择合适的方法即可。函数封装后更便于在项目中复用。
上一篇:重返未来1999礼包码最新分享
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9