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)

删除字符串指定前后的几个字符

idcard = "12345"
idcard = idcard[1:-1]

print(idcard)    # 234

strip

参数

  • chars -- 移除字符串头尾指定的字符序列。

返回值

返回移除字符串头尾指定的字符序列生成的新字符串。

#!/usr/bin/python3
 
str = "*****this is **string** example....wow!!!*****"
print (str.strip( '*' ))  # 指定字符串 *


结果:
this is **string** example....wow!!!

split

参数

  • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num -- 分割次数。默认为 -1, 即分隔所有。

返回值

返回分割后的字符串列表。

#!/usr/bin/python3
 
str = "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/python3

str = "     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/python3

str = "     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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨痕诉清风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值