> For the complete documentation index, see [llms.txt](https://stb11816.gitbook.io/python_note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stb11816.gitbook.io/python_note/crawler/kong-zhi-zi-7b2628-control-character.md).

# 控制字符(control character)

看不到但確實存在的幽靈字符，可使用re進行替換，比replace來的方便些

## re

```python
# python3
import re
text = '你\u202a好阿\u202e陌生人'  # 參雜控制字符
print(text, [text], len(text))  # 長度為8 (6+2)

# 將特定範圍的符號替換為空字串
str_input = re.sub(r'[\u200b-\u200f \u2029-\u202e \u2061-\u2064 \u206a-\u206f]', "", text)

print(str_input, [str_input], len(str_input))  # 長度為2
```

## 檢查控制符號內容

在python3可使用內建函數來查看字符編碼與內容

ord(str)：回傳在unicode中的對應編號

chr(int)：回傳編號所對應的unicode

目前遇到的幽靈字符範圍如下：

| 字符                 | 編碼         |
| ------------------ | ---------- |
| "\u200b"\~"\u200f" | 8203\~8207 |
| "\u2029"\~"\u202e" | 8233\~8239 |
| "\u2061"\~"\u2064" | 8289\~8292 |
| "\u206a"\~"\u206f" | 8298\~8303 |

```python
# python3
# 輸出編碼與字符
for i in range(8000, 9000):
    print(chr(i), ord(chr(i))) # 字符, 編碼
```

奇怪的空格

| 字符       | 編碼           |
| -------- | ------------ |
| "\u3000" | 12288 (全形空格) |
| "\u202f" | 8239         |
| "\u205f" | 8287         |
| "\xa0"   | 160          |

替換空格

```python
# python3
import re
text = '你\u202a\u202a好阿\u202e陌生\u202f人'  # 參雜控制字符
print(text, [text], len(text))  # 長度為8 (6+2)
str_input = re.sub(r'[\u202f\u205f\u3000]', " ", text)
print(str_input, [str_input], len(str_input))
```

參考資料：\
<https://www.itread01.com/article/1486433903.html>\
<https://dotblogs.com.tw/law1009/2013/07/13/109833>\
<https://www.programcreek.com/python/example/144/re.VERBOSE>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://stb11816.gitbook.io/python_note/crawler/kong-zhi-zi-7b2628-control-character.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
