在 Python 中获取从索引到字符串末尾的子字符串
Get substring from index to end of string in Python
使用字符串切片获取从索引到字符串末尾的子字符串,例如result = my_str[index:]
. 如果stop
未指定索引值,则切片会转到字符串的末尾。
my_str = 'bobbyhadz' # 👇️ get index of first occurrence of character index = my_str.index('h') result = my_str[index:] print(result) # 👉️ 'hadz' # ------------------------------------ # 👇️ get index of last occurrence of character last_index = my_str.rindex('b') print(my_str[last_index:]) # 👉️ 'byhadz'
我们使用字符串切片来获取从索引到字符串末尾的子字符串。
字符串切片的语法是my_str[start:stop:step]
.
start
,而stop
索引是排他的(最多,但不包括)。Python 索引是从零开始的,因此字符串中的第一个字符的索引为0
,最后一个字符的索引为-1
or len(my_str) - 1
。
我们可以通过省略stop
索引来获取到字符串末尾的切片。
my_str = 'bobbyhadz' index = my_str.index('h') result = my_str[index:] print(result) # 👉️ 'hadz'
索引的值stop
是独占的(最多但不包括),因此如果您指定索引-1
,字符串中的最后一个字符将不会包含在切片中。
my_str = 'bobbyhadz' index = my_str.index('h') result = my_str[index:-1] print(result) # 👉️ 'had'
切片上升到但不包括字符串中的最后一个字符。
str.index
方法返回字符串中提供的子字符串第一次出现的索引。
ValueError
如果在字符串中找不到子字符串,则该方法会引发 a 。You can use a try/except
block to handle the scenario where the substring is
not found in the string.
my_str = 'bobbyhadz' try: index = my_str.index('X') result = my_str[index:] print(result) except ValueError: # 👇️ this runs print('The substring is not contained in the string')
The except
block handles the ValueError
if the substring is not contained in
the string.
The str.index()
method returns the index of the first occurrence of the given
substring in the string.
If you need to get the index of the last occurrence, use the str.rindex()
method.
my_str = 'bobbyhadz' last_index = my_str.rindex('b') print(my_str[last_index:]) # 👉️ 'byhadz'
The str.rindex
method returns the highest index in the string where the provided substring is
found.
The rindex()
method also raises a ValueError
if the substring is not
contained in the string.