首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从引号之间提取字符串

从引号之间提取字符串
EN

Stack Overflow用户
提问于 2010-01-16 13:53:08
回答 3查看 78.5K关注 0票数 35

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

SetVariables "a" "b" "c"

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-01-16 13:58:24

>>> import re
>>> re.findall('"([^"]*)"', 'SetVariables "a" "b" "c" ')
['a', 'b', 'c']
票数 54
EN

Stack Overflow用户

发布于 2010-01-16 14:16:45

您可以对其执行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
票数 37
EN

Stack Overflow用户

发布于 2010-01-16 13:58:29

Regular expressions擅长这一点:

import re
quoted = re.compile('"[^"]*"')
for value in quoted.findall(userInputtedText):
    print value
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2076343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档