python如何用函数删除空白

使用strip()删除两端空白:def remove_spaces_both_sides(text): return text.strip();2. lstrip()删左侧空白;3. rstrip()删右侧空白;4. replace()或re.sub(r"\s+", "")删所有空白字符,可封装函数复用。

在Python中,删除字符串中的空白可以使用内置的字符串方法,而不是自定义函数。但你可以将这些方法封装在函数中,方便重复调用。以下是几种常见的删除空白的方式及对应的函数写法。

1. 删除两端空白(空格、换行、制表符)

使用 strip() 方法可以去除字符串开头和结尾的空白字符。

def remove_spaces_both_sides(text): return text.strip()

示例

s = " hello world " print(remove_spaces_both_sides(s)) # 输出: "hello world"

2. 删除左边空白

使用 lstrip() 去除字符串左侧的空白。

def remove_left_space(text): return text.lstrip()

示例

s = " hello world " print(remove_left_space(s)) # 输出: "hello world "

3. 删除右边空白

使用 rstrip() 去除字符串右侧的空白。

def remove_right_space(text): return text.rstrip()

示例

s = " hello world " print(remove_right_space(s)) # 输出: " hello world"

4. 删除所有空白(包括中间的空格)

如果想删除字符串中所有的空白字符(空格、制表符、换行等),可以用 replace()re.sub()

def remove_all_spaces(text): return text.replace(" ", "")

示例

s = "hello world python" print(remove_all_spaces(s)) # 输出: "helloworldpython"

若还包括制表符、换行符等,可用正则:

import re

def remove_all_whitespace(text): return re.sub(r"\s+", "", text)

示例

s = " hello \t\n world " print(remove_all_whitespace(s)) # 输出: "helloworld"

基本上就这些常用方式。根据你要删除的空白位置和范围选择合适的方法即可。函数封装后更便于在项目中复用。