apppublic/aidocs/strUtils.md
2025-10-05 11:23:33 +08:00

134 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# `strUtils` 模块技术文档
---
## 概述
`strUtils` 是一个简单的 Python 工具模块,提供对字符串进行左右空格去除的基本功能。该模块包含三个函数:
- `rtrim(ss)`:去除字符串右侧的空格。
- `ltrim(ss)`:去除字符串左侧的空格。
- `lrtrim(ss)`:同时去除字符串左右两侧的空格。
这些函数不依赖外部库,适用于基础字符串处理场景。
---
## 函数说明
### `rtrim(ss)`
#### 功能
去除输入字符串右侧的所有空格字符(`' '`),保留其余部分。
#### 参数
- `ss` (str): 待处理的字符串。
#### 返回值
- (str): 去除右侧空格后的字符串。若原字符串为空,返回空字符串。
#### 示例
```python
rtrim("hello ") # 返回 "hello"
rtrim(" hello ") # 返回 " hello"
rtrim("") # 返回 ""
```
#### 实现逻辑
1. 若输入字符串为空,直接返回。
2. 使用循环检查字符串最后一个字符是否为空格,若是则切片去除最后一个字符,重复此过程直到末尾非空格为止。
---
### `ltrim(ss)`
#### 功能
去除输入字符串左侧的所有空格字符(`' '`),保留其余部分。
#### 参数
- `ss` (str): 待处理的字符串。
#### 返回值
- (str): 去除左侧空格后的字符串。若原字符串为空,返回空字符串。
#### 示例
```python
ltrim(" hello") # 返回 "hello"
ltrim(" hello ") # 返回 "hello "
ltrim("") # 返回 ""
```
#### 实现逻辑
1. 若输入字符串为空,直接返回。
2. 使用循环检查字符串第一个字符是否为空格,若是则切片去除第一个字符,重复此过程直到开头非空格为止。
---
### `lrtrim(ss)`
#### 功能
同时去除输入字符串左侧和右侧的所有空格字符。
#### 参数
- `ss` (str): 待处理的字符串。
#### 返回值
- (str): 去除左右空格后的字符串。若原字符串为空,返回空字符串。
#### 示例
```python
lrtrim(" hello ") # 返回 "hello"
lrtrim(" hi there ") # 返回 "hi there"
lrtrim("") # 返回 ""
```
#### 实现逻辑
1. 先调用 `ltrim(ss)` 去除左侧空格。
2. 再对结果调用 `rtrim(s)` 去除右侧空格。
3. 返回最终结果。
> **注意**:该函数等效于 Python 内置的 `str.strip()`,但此处为手动实现。
---
## 使用示例
```python
# 导入模块(假设保存为 strUtils.py
from strUtils import *
text = " Hello World "
print(repr(rtrim(text))) # ' Hello World'
print(repr(ltrim(text))) # 'Hello World '
print(repr(lrtrim(text))) # 'Hello World'
```
---
## 注意事项
- 本模块仅处理空格字符(`' '`),不处理其他空白字符(如制表符 `\t`、换行符 `\n` 等)。
- 对于大字符串或高频调用场景,建议使用 Python 内置方法 `str.strip()`, `str.lstrip()`, `str.rstrip()`,性能更优。
- 输入参数应为字符串类型,否则可能引发 `IndexError``TypeError`
---
## 版本信息
- 创建时间2025年4月
- 作者:匿名
- 许可:公共领域 / 自由使用
---
## 扩展建议
未来可扩展如下功能:
- 支持去除多种空白字符(使用 `string.whitespace`)。
- 添加 `trim_all(ss)` 函数用于去除所有连续空格并压缩为单个空格。
- 增加类型检查与异常处理机制。
---
**提示**:虽然此模块可用于学习字符串操作原理,但在生产环境中推荐优先使用 Python 内置的 `strip` 系列方法。