[Tutor] manipulating a string in python
Albert-Jan Roskam
fomcl at yahoo.com
Tue Nov 27 21:38:46 CET 2012
<snip>
'
>
>import re
>media_re = re.compile(r'(auto|10+T-[HF]D)')
>
>instr = """tmsh list net interface 1.1 media-capa \rbilities\nnet
>interface 1.1
>{\n media-capabilities {\n none\n auto\n 10T-FD\n
>10T-HD\n 100TX-FD\n 100TX-HD\n 1000T-FD\n
>1000T-HD\n }\n}\n"""
>
>print [ x.strip() for x in instr.split() if media_re.match(x) ]
>
>
>gives:
>['auto', '10T-FD', '10T-HD', '1000T-FD', '1000T-HD']
slightly more readable:
print re.findall(r'(auto|10+T-[HF]D)', instr)
gives:
['auto', '10T-FD', '10T-HD', '1000T-FD', '1000T-HD']
Not relevant here, but really neat (I recently discovered this by accident): if you have groups in your regex, re.findall turns them into a list of tuples.
>
More information about the Tutor
mailing list