1

I have a "raw" variable that store:

*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"

Is it possible that I store the word in a array with front and back double quotes as a delimiter?

I unable to use " as delimiter.

Example:

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"]

Note:

  • There are different spacing (including \n) between the word.
  • I will be storing into 2D array after the formattedArray.
3
  • 1
    What problems are you having? Your example code works fine. Oct 28, 2011 at 9:44
  • @DavidHeffernan What example code? I think he wants to for the array from his raw variable.
    – unni
    Oct 28, 2011 at 9:50
  • Please be more explicit about the format of rawVariable. Is it a string defined that way in a line of python (in which case it is just the individual substrings concatenated, and you will have to split on capital letters)? Or is that the actual string including quotation marks? Oct 28, 2011 at 9:57

2 Answers 2

1

I'm not 100% sure if I understand your question, but I'm guessing the following code might help you:

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)

gives the following output:

['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']

Is that what you need?

1
  • Yeah! Thanks! Both answer did the same job (to a certain extent) but I prefer this because it is more solid.
    – Ezylryb
    Oct 30, 2011 at 15:13
1

It seems to me that you just need to split the string via " delimeter and get every other substring (since the interesting ones will be interwined with whitespace):

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

Testing appears to yield correct results:

>>> 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']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.