>>> s = 'SetVariables "a" "b" "c"';
>>> l = s.split('"')[1::2]; # the [1::2] is a slicing which extracts odd values
>>> print l;
['a', 'b', 'c']
>>> print l[2]; # to show you how to extract individual items from output
c
这也是一种比正则表达式更快的方法。使用timeit模块,此代码的速度大约快4倍:
% python timeit.py -s 'import re' 're.findall("\"([^\"]*)\"", "SetVariables \"a\" \"b\" \"c\" ")'
1000000 loops, best of 3: 2.37 usec per loop
% python timeit.py '"SetVariables \"a\" \"b\" \"c\"".split("\"")[1::2];'
1000000 loops, best of 3: 0.569 usec per loop
Regular expressions擅长:
你可以在上面做一个string.split()。如果字符串使用引号(即引号的偶数)正确格式化,则列表中的每个奇数值都将包含引号之间的元素。
这也是一种比正则表达式更快的方法。使用timeit模块,此代码的速度大约快4倍:
相关问题 更多 >
编程相关推荐