python基础教程:字符串操作rstrip()&strip()&lstrip()

提示:本篇包含rstrip()方法、strip()方法


一、rstrip()方法

1.1 用途描述

  rstrip() 删除 string 字符串末尾的指定字符(默认为空格)

1.2 语法

  str.rstrip([chars]);
  参数:chars -指删除的字符;
  返回值:是返回删除 string 字符串末尾的指定字符后生成的新字符串。

1.3 实例

str = "     this is a apple!     "
print (str.rstrip())
str = "*****this is a apple!*****"
print (str.rstrip('*'))
------------------------------------------------------
## 输出为:
     this is a apple!
*****this is a apple!

二、strip()方法

2.1 用途描述

  strip() 方法:用于移除字符串头尾指定的字符(默认为空格)或字符序列。注:只能删除开头或是结尾的字符,不能删除中间部分的字符。

2.2 语法

  str.strip([chars]);
  参数:chars --移除字符串头尾指定的字符序列;
  返回值:返回移除字符串头尾指定的字符序列生成的新字符串。

2.3 实例

str = "*****this is **a ** apple!*****"
print (str.strip('*'))
---------------------------------
## 输出为:
this is **a ** apple!

三、lstrip() 方法

3.1 用途描述

  用于截掉字符串左边的空格或指定字符

3.2 语法

  str.lstrip([chars])
  参数:chars -指定截取的字符;
  返回值:返回截掉字符串左边的空格或指定字符后生成的新字符串。

3.3 实例

str = "     this is a apple!     ";
print( str.lstrip() );
str = "*******this is a apple!*******";
print( str.lstrip("*") );
--------------------------------------------
## 输出为:
this is a apple!
this is a apple!*******

总结

  新学的两个字符串的操作方法,记录一下,可用于数据的预处理。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

梦想拯救世界_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值