Re: How do I parse a string to a tuple??



On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote:

Hi!

I have a string that contains some text and newline characters. I want
to parse the string so that the string just before a newline character
goes in as an element in the tuple.

ex:

"text1 \n text2 \n text3 \n text4" --> (text1, text2, text3, text4)

Is there an easy way to do this?

the_string = "text1 \n text2 \n text3 \n text4"
tuple(the_string.split('\n'))

If you don't need a tuple, and a list will do:

the_string.split('\n')

If you want to get rid of the white space after each chunk of text:

[s.strip() for s in the_string.split('\n')]




--
Steven D'Aprano

.



Relevant Pages

  • retaining newline characters when writing to file
    ... If I read a string that contains a newline characterinto a variable, then write that variable to a file, how can I retain those newline characters so that the string remains on one line rather than spans multiple lines? ... I'm reading the address field from an HTML form. ... (Or is it better to just use separate text fields for each line of the address?) ...
    (comp.lang.python)
  • Re: Pattern Matching
    ... I'm trying to find out how many newline characters are in a string. ... > Do I need to step through the string a character at a time to check this? ... file with 11 newlines, which I read into a string. ... A language is therefore a horizon, and style a vertical dimension, which together map out for the writer a Nature, since he does not choose either. ...
    (perl.beginners)
  • Re: using regular expressions with find and replace in VC++
    ... This will allow them to act as a delimiters. ... putting \n in the replace string should work (it ... newline characters in the original function and insert them in the modified ...
    (microsoft.public.vc.language)
  • Re: Regex greedy/lazy problem
    ... I suspected that you might simply be trying to parse each bit that comes ... you have a string ending with the end tag. ... second string buffer and putting each chunk received into it. ...
    (microsoft.public.dotnet.general)
  • Re: Selective splits... (treat this "pattern" as a delimiter only if it is followed by this "pattern
    ... Your string must be a single line; no newline characters. ... print a newline for every even numbered element _after_ zero element ... Plus increment counter ...
    (perl.beginners)