python删除字符串_Python3 - 删除字符串中不需要的字符
生活随笔
收集整理的這篇文章主要介紹了
python删除字符串_Python3 - 删除字符串中不需要的字符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
去掉文本字符串開頭,結尾或者中間不想要的字符,比如空白。
解決方案
strip() 方法用于刪除字符串開始或結尾的字符。 lstrip() 和 rstrip() 分別從左和從右執行刪除操作。 默認情況下,這些方法會刪除空白字符,但是你也可以指定其他字符。比如:
case-1
s = ' hello world \n'
print(s.strip())
print(s.lstrip()) # 換行符在print輸出后,會自動換行
print(s.rstrip())
hello world
hello world
hello world
case-2
t = '-----hello====='
print(t.strip('-='))
print(t.lstrip('-'))
print(t.rstrip('='))
hello
hello=====
-----hello
討論
需要注意的是去除操作不會對字符串的中間的文本產生任何影響。比如:
ss = ' hello world \n'
print(ss.strip())
hello world
如果需要刪除字符串中間的空格,可以使用 replace() 方法或者是用正則表達式替換。示例如下:
ss = 'hello world\n'
print(ss.replace(' ', ''))
hello world
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python删除字符串_Python3 - 删除字符串中不需要的字符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一加11国际版亮相GeekBench 全
- 下一篇: python扇贝单词书_Python脚本