如何拆分含有多種分隔符的字串
zero, one, two, three, fous, five, six, seven, eight, nine = range(10)"""author:cairo
"""'''
實際案例:
我們要把某個字串依據分隔符號拆分不同的字段,
該字串包含多種不同的分隔符,例如:
s='ab;cd|ef+hi,/ds\aef;sdfe.usad\txyz'
''''''
解決方案:
方法一:連續使用是str.split()方法,每次處理一種分隔符號。
方法二:使用正規表示式的re.split()方法,一次性拆分字串。
'''#
def mysplit(s,ds):
#res = [s]
#for i in ds:
#t =
#map(lambda x:t.extend(x.split(i)) , res)
#res = t
#return res
s='ab;cd|ef+hi,/ds\tef;sd fe.usad\txyz'#
print(mysplit(s,';|/,.\t'))#二:
import
reprint(re.split(r'
[;|/,.\t+ ]+
',s))#
方括號內的是切割符號,方括號外邊的+號是乙個或者多個
#注意:如果只是切割乙個字串就用s.split(),因為這個比正則快
如何判斷字串是a是否以字串b開頭或結尾
zero, one, two, three, fous, five, six, seven, eight, nine = range(10)"""author:cairo
"""'''
使用字串的str.startswith()和str.endswith(可以多個)方法。
注意:多個匹配時引數使用元組
'''import
os , stat
print(os.listdir('
.'))
正則的捕獲與替換
zero, one, two, three, fous, five, six, seven, eight, nine = range(10)"""author:cairo
"""import
relog = ['
2018-05-06
','2017-08-06
','2016-05-08
','2019-01-23']
#for i in log:
#print(re.sub('(\d)-(\d)-(\d)',r'\1/\2/\3',i))
'''返回的是乙個位址,要看看需求來定了
#使用匿名函式解析
# nima = map(lambda x:re.sub('(\d)-(\d)-(\d)',r'\1/\2/\3',x),log)
# print(nima)
# 使用map+lambda返回位址
# nima = filter(lambda x:re.sub('(\d)-(\d)-(\d)',r'\1/\2/\3',x),log)
# print(nima)
# 使用filter+lambda返回位址
'''#
列表解析
print([x for x in log if re.sub('
(\d)-(\d)-(\d)
',r'
\1/\2/\3
',x)])
''':r'\1/\2/\3':替換前面的,捕獲組
:r:原始字串
'''#
還可以給每個組取名
for i in
log:
print(re.sub('
(?p\d)-(?p\d)-(?p\d)
',r'
\g/\g/\g
',i))
posted @
2018-05-26 16:19
caionk 閱讀(
...)
編輯收藏
字串演算法訓練
1.題目 請編寫乙個c函式,該函式將乙個字串逆序 include include include void change char str c 0 printf s n c strlen begin void main printf 輸入乙個字串 n scanf s b change b 2 inc...
字串操作 靠字串分割字串
字串分解函式。注意strtok比較複雜。要妥善運用!也可以不用strtok函式,但要實現字串靠字串分割比較困難!注意str指向的空間必須是可讀可寫的 如陣列或動態分配的空間 不能為字串常量的指標,因為strtok改變了其中的內容。include include 功能 將str中的字串按照elemon...
字串的操作
strcpy,sprintf,memcpy的區別 對於字串拷貝來說,其實現的效率和使用的方便程度不同 strcpy 無疑是最合適的選擇 效率高且呼叫方便。snprintf 要額外指定格式符並且進行格式轉化,麻煩且效率不高。memcpy 雖然高效,但是需要額外提供拷貝的記憶體長度這一引數,易錯且使用不...