Python操作字符串

时间:2011-10-28 09:36:38

标签: python string delimiter

我有一个“原始”变量存储:

*rawVariable =* "Hello" "World"  "String 1"  "String 2"  "String 3"  "Sting 4"   
"Hello" "World"  "String 5"  "String 6"  "String 7"  "String 8"   
"Hello" "World" "String 9"  "String 10"  "String 11"  "String 12"

我是否有可能将单词存储在前后双引号作为分隔符的数组中?

我无法使用"作为分隔符。

示例:

formattedArray = ["Hello","World","String 1","String 2","String
3","Sting 4","Hello","World"  "String 5","String 6","String 7","String
8","Hello","World","String 9","String 10","String 11","String 12"]

注意:

  • 单词之间有不同的间距(包括\n)。
  • 我将在formattedArray之后存储到2D数组中。

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题,我不是百分百肯定,但我猜这些代码可能会对你有所帮助:

import re

def splitRawString(s):
    return map(lambda x: re.sub('^"?([^"]*)"?$', r'\1', x),
        re.split('"\s*"', s))

a='"Hello" "World" "String 1" "String 2" "String 3" "Sting 4" "Hello" "World" "String 5" "String 6" "String 7" "String 8" "Hello" "World" "String 9" "String 10" "String 11" "String 12"'
print splitRawString(a)

给出以下输出:

['Hello', 'World', 'String 1', 'String 2', 'String 3', 'Sting 4', 'Hello', 'World', 'String 5', 'String 6', 'String 7', 'String 8', 'Hello', 'World', 'String 9', 'String 10', 'String 11', 'String 12']

这就是你需要的吗?

答案 1 :(得分:1)

在我看来,你只需要通过"分隔符拆分字符串并获取所有其他子字符串(因为有趣的子字符串将与空格交织):

def split_quoted_strings(s):
    split_via_quote = s.split('"')
    return split_via_quote[1::2]

测试似乎产生了正确的结果:

>>> a='"Hello" "World" "String 1" "String 2" "String 3" "Sting 4" "Hello" "World" "String 5" "String 6" "String 7" "String 8" "Hello" "World" "String 9" "String 10" "String 11" "String 12"'
>>> split_quoted_string(a)
['Hello',
'World',
# omitted
'String 12']