想要移除字符串头尾的特定字符或者字符序列,我们需要用到.strip()
和它的左臂.lstrip()
右膀.rstrip()
。接下来通过例子来详细说明。
- ()里面什么都不放时,默认去除空格或换行符
str0 = " python " print(str0.strip()) print(str0.lstrip()) print(str0.rstrip()) # 结果如下: "python" "python " " python"
- ()里面放特定字符时,去除该字符
str1 = "0000000python0000000" print(str1.strip('0')) print(str1.lstrip('0')) print(str1.rstrip('0')) # 结果如下: "python" "python0000000" "0000000python"
- ()里面放特定字符序列时,去除该字符序列
str2 = "123python321" print (str2.strip('12')) print (str2.lstrip('12')) print (str2.rstrip('12')) # 结果如下: "3python3" "3python321" "123python3"
来源:CSDN
作者:叫我咸鱼就好
链接:https://blog.csdn.net/yitanjiong4414/article/details/104207440