在字串列表中找出與s最長字首匹配的字串

2021-08-14 09:49:52 字數 428 閱讀 5071

在字串列表中找出與s最長字首匹配的字串

def

closest_match

(s, str_list):

""" 在字串列表中找出與s最長字首匹配的字串

:param s:

:param str_list:

:return: 如果沒有任何匹配則返回空串,否則返回最長字首匹配

"""closest = ""

for str in str_list:

if s.startswith(str):

if closest:

if len(str) >= len(closest):

closest = str

else:

closest = str

return closest

字串 列表中查詢出某個值且對應的下標

1 字串中查詢值和對應的下標 a 123yui78y8y67tuy print re.findall y a 查詢出在a包含的字串中所有的y值 print i for i,x in enumerate a if x y 查詢出a包含的y值所對應的下標 結果 y y y y 3,8,10,15 2 列...

字串 列表和元組的相同與不同

python 表示式 以列表為例 結果描述 len 1,2,3 3長度 1,2,3 4,5,6 1,2,3,4,5,6 組合 hi 4 hi hi hi hi 重複3 in 1,2,3 true 元素是否存在於列表中 for x in 1,2,3 print x,end 1 2 3 迭代python...

python 獲取字串列表中的隨機字串

下面的方法將獲取某個字串列表中的隨機字串 import random defrandomtext textarr length len textarr if length 1 return if length 1 return str textarr 0 randomnumber random.ra...