📌  相关文章
📜  Python|后字符串中出现的第一个字符

📅  最后修改于: 2022-05-13 01:54:30.489000             🧑  作者: Mango

Python|后字符串中出现的第一个字符

有很多方法可以找出 String 中元素的第一个索引,因为Python在其语言中提供了 index()函数,该函数返回 String 中元素第一次出现的索引。但是,如果想要获取字符串中元素的最后一次出现,通常必须应用更长的方法。让我们讨论一些速记来完成这个特定的任务。

方法 #1:使用rfind()
这通常是我们可以用来完成此任务的技巧。使用字符串函数rfind() 从右边获取第一个元素,即字符串中元素的最后一个索引。

# Python 3 code to demonstrate 
# First character occurrence from rear String
# using rfind()
  
# initializing string
test_str = "Geeksforgeeks"
  
# printing original string
print ("The original string is : " + str(test_str))
  
# using rfind()
# to get last element occurrence
res = test_str.rfind('e')
  
# printing result
print ("The index of last element occurrence: " + str(res))
输出 :
The original string is : Geeksforgeeks
The index of last element occurrence: 10

方法 #2:使用列表切片 + index() + list()
可以使用 list() 将字符串转换为列表,然后使用列表切片我们反转列表并使用常规索引方法获取元素第一次出现的索引。由于反向列表,返回最后一次出现而不是列表的第一个索引。

# Python 3 code to demonstrate 
# First character occurrence from rear String 
# using List Slice + index() + list()
  
# initializing string
test_str = "Geeksforgeeks"
  
# printing original string
print ("The original string is : " + str(test_str))
  
# using List Slice + index() + list()
# First character occurrence from rear String
test_str = list(test_str)
res = len(test_str) - 1 - test_str[::-1].index('e')
  
# printing result
print ("The index of last element occurrence: " + str(res))
输出 :
The original string is : Geeksforgeeks
The index of last element occurrence: 10