class GameRole:
def __init__(self, nm, wp):
self.name = nm
self.weapon = wp
if __name__ == '__main__':
lb = GameRole('呂布', '方天畫戟') # 創建名為lb的實例
print(lb.name, lb.weapon)
類中有一些以雙下劃線開頭和結尾的特殊方法,也稱作magic魔法方法。
https://jex.im/regulex
# 將mac地址加上冒號
192.168.1.1 000C29123456
192.168.1.2 525400A31B2C
192.168.1.3 0002231A08D3
# 思路:找到mac地址、每兩個數分一組、組之間加冒號
:%s/\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1:\2:\3:\4:\5:\6/
re模塊常用方法
>>> import re
# match匹配到,返回匹配對象,否則返回None
>>> re.match('f..', 'food')
<_sre.SRE_Match object; span=(0, 3), match='foo'>
>>> print(re.match('f..', 'seafood'))
None
# search在字符串中匹配
>>> re.search('f..', 'food')
<_sre.SRE_Match object; span=(0, 3), match='foo'>
>>> re.search('f..', 'seafood')
<_sre.SRE_Match object; span=(3, 6), match='foo'>
>>> m = re.search('f..', 'seafood')
>>> m.group() # 匹配對象的group方法返回匹配到的字符串
'foo'
# findall可以匹配到所有的內容
>>> re.findall('f..', 'seafood is food')
['foo', 'foo']
# finditer返回匹配對象的迭代器
>>> list(re.finditer('f..', 'seafood is food'))
[<_sre.SRE_Match object; span=(3, 6), match='foo'>, <_sre.SRE_Match object; span=(11, 14), match='foo'>]
>>> for m in re.finditer('f..', 'seafood is food'):
... m.group()
...
'foo'
'foo'
# split用於切割
# 以.或-作為分隔符
>>> re.split('\.|-', 'how-are-you.tar.gz')
['how', 'are', 'you', 'tar', 'gz']
# 替換
# 將X替換為python
>>> re.sub('X', 'python', 'X is good. I like X.')
'python is good. I like python.'
# 當有大量匹配時,提前把模式進行編譯,可以得到更好的效率
>>> patt = re.compile('f..')
>>> patt.search('seafood')
<_sre.SRE_Match object; span=(3, 6), match='foo'>
>>> m = patt.search('seafood')
>>> m.group()
'foo'
>>> patt.findall('seafood is food')
['foo', 'foo']