By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,095 Members | 1,586 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,095 IT Pros & Developers. It's quick & easy.

How do I parse a string to a tuple??

P: n/a
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?

Thanks!,
Soren

Apr 30 '07 #1
Share this Question
Share on Google+
5 Replies


P: n/a
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

Apr 30 '07 #2

P: n/a
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, text2, text3, text4)

Is there an easy way to do this?

Thanks!,
Soren
For this particular, very narrow, example, following the example as
closely as I possibly can:

import re

atext = "text1 \n text2 \n text3 \n text4"
atup = tuple(re.split(r'\s*\n', atext))

James
Apr 30 '07 #3

P: n/a
On Apr 30, 5:47*pm, Soren <soren.skou.niel...@gmail.comwrote:
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?

Thanks!,
Soren
tuple("text1 \n text2 \n text3 \n text4".split('\n'))

Apr 30 '07 #4

P: n/a
Steven D'Aprano wrote:
On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote:
>"text1 \n text2 \n text3 \n text4" --(text1, text2, text3, text4)

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')
or the_string.splitlines()
If you want to get rid of the white space after each chunk of text:

[s.strip() for s in the_string.split('\n')]
--
Michael Hoffman
Apr 30 '07 #5

P: n/a

Thanks alot everyone!

Soren

Apr 30 '07 #6

This discussion thread is closed

Replies have been disabled for this discussion.