删除字符串某字符后的字符串
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