📌  相关文章
📜  Python –字符串中 K 的中间出现

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

Python –字符串中 K 的中间出现

给定一个字符串,任务是编写一个Python程序来提取字符的中间出现。

方法 #1:使用enumerate() +列表理解

在这里,我们执行使用列表推导获取所有出现的任务,并枚举获取所有索引。发布列表的中间元素被打印以获取字符的中间出现。

Python3
# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using find() + max() + slice
  
# initializing string
test_str = "geeksforgeeks is best for all geeks"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = 'e'
  
# getting all the indices of K
indices = [idx for idx, ele in enumerate(test_str) if ele == K]
  
# getting mid index
res = indices[len(indices) // 2]
  
# printing result
print("Mid occurrence of K : " + str(res))


Python3
# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using finditer() + list comprehension + regex
import re
  
# initializing string
test_str = "geeksforgeeks is best for all geeks"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = 'e'
  
# getting all the indices of K
# using regex
indices = [ele.start() for ele in re.finditer(K, test_str)]
  
# getting mid index
res = indices[len(indices) // 2]
  
# printing result
print("Mid occurrence of K : " + str(res))


输出:

The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10

方法#2:使用 finditer() +列表理解+正则表达式

在这种情况下,使用正则表达式和 finditer() 找到该字符。中间出现是索引列表的中间元素。

蟒蛇3

# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using finditer() + list comprehension + regex
import re
  
# initializing string
test_str = "geeksforgeeks is best for all geeks"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing K
K = 'e'
  
# getting all the indices of K
# using regex
indices = [ele.start() for ele in re.finditer(K, test_str)]
  
# getting mid index
res = indices[len(indices) // 2]
  
# printing result
print("Mid occurrence of K : " + str(res))

输出:

The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10