欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python删除、替换字符串某字符后的字符串(删除字符串、替换字符串、strip、split、rstrip、lstrip、replace)

发布时间:2025/3/15 python 31 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。