- Python進階編程:編寫更高效、優雅的Python代碼
- 劉宇宙 謝東 劉艷
- 476字
- 2021-04-30 12:39:37
2.2.2 刪除不需要的字符
去除字符串中一些不需要的字符,是在工作中經常碰到的操作,比如去除空格。
strip()方法用于刪除開始或結尾的字符。lstrip()和rstrip()方法分別從左和右執行刪除操作。默認情況下,這些方法會去除空字符,也可以指定其他字符,相關代碼(delete_str.py)示例如下:
test_str = ' hello world \n ' print(f'去除前后空格:{test_str.strip()}') print(f'去除左側空格:{test_str.lstrip()}') print(f'去除右側空格:{test_str.rstrip()}') test_t = '===== hello--world-----' print(test_t.rstrip('-')) print(test_t.strip('-='))
執行py文件,輸出結果如下:
去除前后空格:hello world 去除左側空格:hello world 去除右側空格: hello world ===== hello--world hello--world
strip()方法經常會被用到,如用來去掉空格、引號。
注意:去除操作不會對字符串的中間的文本產生任何影響。
如果想處理字符串中間的空格,需要求助其他方法,如使用replace()方法或者使用正則表達式,代碼示例如下:
print(test_s.replace(' ', '')) import re print(re.sub('\s+', '', test_s))
通常情況下,我們可以將字符串strip操作和其他迭代操作相結合,如從文件中讀取多行數據,此時使用生成器表達式就非常好,相關代碼示例(delete_str.py)示例如下:
file_name = '/path/path' with open(file_name) as file: lines = (line.strip() for line in file) for line in lines: print(line)
示例中,表達式lines=(line.strip() for line in file)執行數據轉換操作。這種方式非常高效,不需要預先將所有數據讀取到一個臨時列表。它僅僅是創建一個生成器,并且在每次返回行之前會先執行strip操作。