
上QQ阅读APP看书,第一时间看更新
练习13:字符串切片
与列表一样,我们可以对字符串进行切片。
1.创建一个字符串str_1:

2.指定切片值并切片字符串:

输出如下:

3.通过跳过一个切片值来切片字符串:

输出如下:

4.使用负数来分割字符串:

输出如下:

字符串函数
为了获取字符串长度,我们使用了len函数。

字符串的长度是41。为了转换字符串的大小写,我们用了lower和upper方法:

输出如下:

为了从字符串中搜索指定字符串,我们用了find方法:

输出为-1。你清楚find方法是否区分大小写吗?另外,你知道find方法在实际找到该字符串时返回什么吗?
为了用一个字符串替换另一个字符串,我们用了replace方法。由于字符串是一个不可变的数据结构,replace方法返回了一个新的字符串,而不是替换和返回实际的字符串:

输出如下:

若想要了解更多关于这些方法的使用,可在Python 3标准文档中查找字符串方法。