Python小记:3.Python中字符串空格无法由strip、replace方法删除问题

str_unit=" 校 训:自 强不强息、厚德载物。  "
str_sub="校训"
str_unit.strip()#清空字符串中的空格
print(str_unit)
print(str_unit.startswith(str_sub))#检查str_unit是否是以str_sub开头

讲道理,应该空格全删除,判断返回TRUE了

 校 训:自 强不强息、厚德载物。  
False
Press any key to continue . . .

于是又换了一种方式删除空白格:

str_unit=" 校 训:自 强不强息、厚德载物。  "
str_sub="校训"
#str_unit.strip()
str_unit.replace(" ","")#将空格替换为空
print(str_unit)
print(str_unit.startswith(str_sub))
 校 训:自 强不强息、厚德载物。  
False
Press any key to continue . . .


结果还是没有正常删除,这是为什么呢???

首先,要注意的是中英文的空格是不一样的。

与上段代码思路相同,细节上是用新变量str03来接受之前replace方法的返回值,然后打印str_unit和str03的结果运行

str_unit=" 校 训:自 强不强息、厚德载物。  "
str_sub="校训"
# str_unit.strip(' ')
str03=str_unit.replace(" ","")
print(str_unit)
print(str03)
print(str03.startswith(str_sub))

这次运行的结果,符合我们去掉空格的预期

/usr/bin/python3.5 /home/tarena/pycode/day0102/08/字符串.py
 校 训:自 强不强息、厚德载物。  
校训:自强不强息、厚德载物。
True

值得注意的是,str03在调用replace方法后,原字符串并没有改变。这是为什么呢?
因为,str_unit是一个变量,指向了开辟的连续空间:
" 校 训:自 强不强息、厚德载物。  ",在Python中,字符串一旦定义就不可变了。
当我们要对其修改时,实际上是重新创建了一个它的副本,并根据要求对其修改。

这里replace函数返回的就是这个副本,但是之前并没有用变量去接受,str_unit本身没有改变。

所以需要创建一个新变量str03来接收replace方法返回的副本

下面是replace方法的定义:

def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
        
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值