从引用之间提取字符串

2024-05-16 23:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从用户输入的文本中提取信息。假设我输入以下内容:

SetVariables "a" "b" "c"

如何在第一组报价之间提取信息?那么第二个呢?那么第三个呢?


Tags: 用户文本信息报价setvariables
3条回答

Regular expressions擅长:

import re
quoted = re.compile('"[^"]*"')
for value in quoted.findall(userInputtedText):
    print value

你可以在上面做一个string.split()。如果字符串使用引号(即引号的偶数)正确格式化,则列表中的每个奇数值都将包含引号之间的元素。

>>> 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
>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']

相关问题 更多 >