📜  Python – 切片字符串中 K 的频率

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

Python – 切片字符串中 K 的频率

给定一个字符串,在索引范围内查找某个字符的频率。

方法 #1:使用切片和 count()

在此,我们使用切片操作对所需字符串进行切片,然后使用 count() 获取该切片字符串中 K 的计数。

Python3
# Python3 code to demonstrate working of
# Frequency of K in sliced String
# Using slicing + count()
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = 3, 20
 
# initializing K
K = 'e'
 
# slicing String
slc = test_str[i : j]
 
# using count() to get count of K
res = slc.count(K)
 
# printing result
print("The required Frequency : " + str(res))


Python3
# Python3 code to demonstrate working of
# Frequency of K in sliced String
# Using Counter() + slicing
from collections import Counter
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = 3, 20
 
# initializing K
K = 'e'
 
# slicing String
slc = test_str[i : j]
 
# Counter() is used to get count
res = Counter(slc)[K]
 
# printing result
print("The required Frequency : " + str(res))


输出
The original string is : geeksforgeeks is best for geeks
The required Frequency : 3

方法 #2:使用 Counter() + 切片

在此,我们使用 Counter() 执行获取计数的任务,切片用于执行范围切片。

Python3

# Python3 code to demonstrate working of
# Frequency of K in sliced String
# Using Counter() + slicing
from collections import Counter
 
# initializing strings
test_str = 'geeksforgeeks is best for geeks'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing i, j
i, j = 3, 20
 
# initializing K
K = 'e'
 
# slicing String
slc = test_str[i : j]
 
# Counter() is used to get count
res = Counter(slc)[K]
 
# printing result
print("The required Frequency : " + str(res))
输出
The original string is : geeksforgeeks is best for geeks
The required Frequency : 3