文本操作方法

1、strip()--去掉每行开头和末尾的换行符 \n 和多余空格
(1)去掉前后空格: " hi ".strip() → "hi"
(2)去掉前后换行符: "\thello\n".strip() → "he llo"
(3)不会去掉中间: " he llo ".strip() → "he llo"
(4)参数是字符集合: "hello world".strip("held") → "o wor"
-----不是完整子串:h、e、l、l、o 从左端被逐个去除,直到遇到空格停止

2、split---分隔符
(1) 默认按空白字符分割
text = "Hello World Python"
print(text.split()) # ['Hello', 'World', 'Python']
(2) 按指定分隔符分割
text = "apple,banana,cherry"
print(text.split(",")) # ['apple', 'banana', 'cherry']
(3)限制分割次数
text = "apple,banana,cherry,grape"
print(text.split(",", 1)) # ['apple', 'banana,cherry,grape']
print(text.split(",", 2)) # ['apple', 'banana', 'cherry,grape']
(4)按换行符分割
text = "line1\nline2\nline3"
print(text.split("\n")) # ['line1', 'line2', 'line3']
(5)多个空白字符自动处理
text = "a b c"
print(text.split()) # ['a', 'b', 'c'] (自动合并连续空白)

posted @ 2026-07-02 15:19  廖生2026  阅读(2)  评论(0)    收藏  举报