Python是一种功能丰富的编程语言,它提供了大量与字符串或文本相关的函数。字符串操作提供了不同的操作,其中
Substring
手术是最重要的手术之一。
什么是子串?
Substring是将获取指定字符串的某些部分的操作。子串操作可以用不同的方式和方法来完成。例如“I love poftut.com”提供子字符串“poftut.com”和“love”等。
串型内置切片
最流行、简单和实用的获取子字符串的方法是使用字符串数据类型切片操作符。字符串类似于字符数组,每个字符都有一个索引号。因此,如果提供这些索引号,则可以从字符串中重新定义某些部分、字符串或子字符串。
SUBSTRING = STRING[START_INDEX:END_INDEX]
STRING
是作为子字符串源并包含字符的文本或字符串。
START_INDEX
是指定子字符串第一个字符的子字符串索引起始编号。起始索引是可选的,如果没有提供,则假定为0。
END_INDEX
是指定子字符串最后一个字符的子字符串索引结束号。结束索引是可选的,如果没有提供,则假定字符串的最后一个字符。
SUBSTRING
返回的子字符串,其中包含字符串中的开始索引号和结束索引号。
从指定索引到结尾的子字符串
让我们从一个关于子字符串的简单示例开始,在这个示例中,我们将指定子字符串的开始索引,而不提供将假定为给定字符串的最后一个字符的结束索引。
s1 = "I love poftut.com"
s1[0:]
# The output is 'I love poftut.com'
s1[1:]
# The output is ' love poftut.com'
s1[2:]
# The output is 'love poftut.com'
s1[5:]
# The output is 'e poftut.com'
s1[55:]
# The output is ''
![图片[1]-如何在Python中使用子字符串?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/07/poftut_image-110.png)
我们可以看到,当我们将起始索引提供为0时,整个comple字符串将作为子字符串返回。如果我们提供的起始索引为55,而给定的字符串不存在,则子字符串为空。
从开始到指定索引的子字符串
由于起始索引是可选的,我们只能为子字符串指定结束索引。默认情况下,起始索引将设置为0。
s1 = "I love poftut.com"
s1[:0]
# The output is ''
s1[:1]
# The output is 'I'
s1[:2]
# The output is 'I '
s1[:5]
# The output is 'I lov'
s1[:55]
# The output is 'I love poftut.com'
![图片[2]-如何在Python中使用子字符串?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/07/poftut_image-111.png)
从指定索引开始到指定索引的子字符串
即使开始索引和结束索引都是可选的,我们也可以同时指定它们。这将使我们能够完全控制子字符串,在这里我们可以显式地设置子字符串的开始和结束索引。
s1 = "I love poftut.com"
s1[0:16]
# The output is 'I love poftut.co'
s1[0:17]
# The output is 'I love poftut.com'
s1[5:17]
# The output is 'e poftut.com'
s1[5:7]
# The output is 'e '
1[7:5]
# The output is ''
![图片[3]-如何在Python中使用子字符串?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/07/poftut_image-112.png)
反向子串
反向子串是一种操作,其中使用负索引号指定子串的开始索引和结束索引。使用负数将反转索引。
s1 = "I love poftut.com"
s1[5:]
# The output is 'e poftut.com'
s1[-5:]
# The output is 't.com'
s1[5:8]
# The output is 'e p'
s1[-5:-8]
# The output is ''
![图片[4]-如何在Python中使用子字符串?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/07/poftut_image-113.png)
使用split()方法生成具有指定字符的子字符串
split()
一个字符串内置函数,可以从给定的字符串中拆分和创建子字符串。Split需要一个Split字符,该字符将像spliter或分隔符一样使用。默认情况下,空格“”是拆分字符,但也可以显式提供给split()函数。
s1 = "I love poftut.com"
s1.split()
# The output is ['I', 'love', 'poftut.com']
s1.split('t')
# The output is ['I love pof', 'u', '.com']
s1.split('.')
# The output is ['I love poftut', 'com']
![图片[5]-如何在Python中使用子字符串?-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/2020/07/poftut_image-114.png)