How do I parse a string to a tuple??

S

Soren

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
 
J

James Stroud

Soren said:
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
 
S

Steven D'Aprano

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

Guest

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'))
 
M

Michael Hoffman

Steven said:
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')]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top