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