python字元串通配符
① 用python解一道通配符匹配的演算法題
假設輸入的字元串為s,匹配串為p,代碼如下
classSolution(object):
defisMatch(self,s,p):
"""
:types:str
:typep:str
:rtype:bool
"""
sIndex,pIndex=0,0
sLen=len(s)
pLen=len(p)
sPrevIndex,pPrevIndex=1,pLen
whilesIndex<sLen:
#當兩個串對應位置字母可以等價時,各自索引均向後
ifpIndex<pLenand(s[sIndex]==p[pIndex]orp[pIndex]=='?'):
sIndex+=1
pIndex+=1
#當模式串為*時,先以匹配0個的方式暫時匹配
elifpIndex<pLenandp[pIndex]=='*':
sPrevIndex=sIndex+1
pPrevIndex=pIndex
pIndex+=1
#當暫時匹配失敗時,以匹配多1個的方式繼續匹配
elifpPrevIndex<pLen:
sIndex,pIndex=sPrevIndex,pPrevIndex
#匹配失敗
else:
returnFalse
#看模式串剩下的字母是否均為*
foriinrange(pIndex,pLen):
ifp[i]!='*':
returnFalse
returnTrue
② Python中的%通配符有什麼使用規則
%這個在字元串中是屬於格式化的一種字元
比如 print( "%d"%2) 這樣輸出的就是 2 %d 就是說輸出數字 後面 就必須跟著 int 型的數字
print("%s"%"你好") 這樣就是輸出 你好 這個字元 這里的%s 就是輸出 字元串 後面跟著的是一個str 類型的參數
print("你好 %s 我今年%d歲"%("張三",12)) 這樣是輸出: 你好張三 我我今年12歲 後面跟著的就是一個元組類型的數據 這個元組 就要求 前面是str 後面是int
關於字元串的格式化還有一個 更加厲害的方法 就是 format() 這個你可以查一下 很多教程
手機碼字 望點贊
③ Python字元串操作的split方法
str.split()沒有參數,代表以空字元分割,空字元包括空格、製表符、回車符、換行符等。因版此,字元串中權的空格和\n都是無參的split()的分割符。Line1-abcdef \nLine2-abc \nLine4-abcd分割後得到['Line1-abcdef', '', 'Line2-abc', '', 'Line4-abcd'],然後,split會拋棄得到的所有空字元串,因此最終結果就是['Line1-abcdef', 'Line2-abc', 'Line4-abcd']。
④ python中字元串拼接
if__name__=='__main__':
result=''
data=['num1','num2','num3','num4']
foriinrange(len(data)):
result+='OR'+'''+data[i]+'''
print(result)
⑤ python正則怎樣匹配出字元串中的字母
r'/"\s*(\w+)\b'
取分組1
⑥ python 通配符匹配如何進行
我覺得你可以使用正則表達式,比如:
importre
p=re.compile('.*.sougou.com')
s="ht.sougou.com!@#$%^&*()"
ifp.match(s):
print'True'
⑦ python中的正則表達式,匹配一串字元串,每一組用;分開每一組裡面是XXXX:like(eq):XXXXX;
|string="lll:zz;sd;a1:like:dd,cc,z1;s:eq:d8;c2:like::e5,42;c:like:88,99";
p=re.compile(r'(?<=;)((?:(?!專:(like|屬eq):).)*:(like|eq):(?:(?!:(like|eq):).)*)(?=(;|$))');
result=p.findall(string);
foreleinresult:
printele[0]
⑧ PYTHON 路徑通配符問題
何必糾結於這細節呢
一是類似的細節太多 根本記不住
其次這些細節不影響功能實現,比如說你要按你的期望方式過濾路徑,那完全可以先把所有路徑得出來,然後再用正則表達式篩選(正則表達式有問題那就是大bug了)
⑨ python字元串運算符
可以使用eval()函數復,表制示執行字元串表示的代碼,例如你這個例子:
a='a'
b='in'
c='abc'
str="a"+b+"c"#拼接為"ainc"
printeval(str)#輸出True
⑩ 在python中,字元串如何進行全字元匹配
import re pattern = re.compile("(?=([a-z]+ [a-z]+))")arry = pattern.findall("a b c d e f g h")
(?=...)匹配不會消耗字元