python删除、替换字符串某字符后的字符串(删除字符串、替换字符串、strip、split、rstrip、lstrip、replace)
生活随笔
收集整理的這篇文章主要介紹了
python删除、替换字符串某字符后的字符串(删除字符串、替换字符串、strip、split、rstrip、lstrip、replace)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
刪除字符串某字符后的字符串
url = "phpmyadmin.css.php?3Fserver=1&lang=en&token=39e3d96974667d6163351cf22870a231&js_frame=right&nocache=3086758583" url = url.split("?", 1)[0] print (url)?
strip
參數
- chars -- 移除字符串頭尾指定的字符序列。
返回值
返回移除字符串頭尾指定的字符序列生成的新字符串。
#!/usr/bin/python3str = "*****this is **string** example....wow!!!*****" print (str.strip( '*' )) # 指定字符串 *結果: this is **string** example....wow!!!?
split
參數
- str -- 分隔符,默認為所有的空字符,包括空格、換行(\n)、制表符(\t)等。
- num -- 分割次數。默認為 -1, 即分隔所有。
返回值
返回分割后的字符串列表。
#!/usr/bin/python3str = "this is string example....wow!!!" print (str.split( )) # 以空格為分隔符 print (str.split('i',1)) # 以 i 為分隔符 print (str.split('w')) # 以 w 為分隔符結果: ['this', 'is', 'string', 'example....wow!!!'] ['th', 's is string example....wow!!!'] ['this is string example....', 'o', '!!!']?
rstrip
參數
- chars -- 指定刪除的字符(默認為空格)
返回值
返回刪除 string 字符串末尾的指定字符后生成的新字符串。
#!/usr/bin/python3str = " this is string example....wow!!! " print (str.rstrip()) str = "*****this is string example....wow!!!*****" print (str.rstrip('*'))結果:this is string example....wow!!! *****this is string example....wow!!!?
lstrip
參數
- chars --指定截取的字符。
返回值
返回截掉字符串左邊的空格或指定字符后生成的新字符串。
#!/usr/bin/python3str = " this is string example....wow!!! "; print( str.lstrip() ); str = "88888888this is string example....wow!!!8888888"; print( str.lstrip('8') );結果: this is string example....wow!!! this is string example....wow!!!8888888?
replace
參數
- old -- 將被替換的子字符串。
- new -- 新字符串,用于替換old子字符串。
- max -- 可選字符串, 替換不超過 max 次
返回值
返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
實例
以下實例展示了replace()函數的使用方法:
#!/usr/bin/python str = "this is string example....wow!!! this is really string"; print str.replace("is", "was"); print str.replace("is", "was", 3);以上實例輸出結果如下:
thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string?
總結
以上是生活随笔為你收集整理的python删除、替换字符串某字符后的字符串(删除字符串、替换字符串、strip、split、rstrip、lstrip、replace)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 各种数据库获取前10行记录实例
- 下一篇: Python输出LOGO图标