[solved] Multiline variable in python

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

[solved] Multiline variable in python

Post by thedotmaster on Sun Jul 27, 2008 2:07 pm
([msg=8422]see [solved] Multiline variable in python[/msg])

Say I have a variable such as this:
Code: Select all
a = "hello\nworld\nlinux\rocks"

it prints like this:
Code: Select all
hello
world
linux
rocks

Now, how can I tell the script just to display the first line, or the second line or whatever?
Would I have to use IF statements and loops or is there a function?
Image
User avatar
thedotmaster
Contributor
Contributor
 
Posts: 984
Joined: Sun May 04, 2008 4:39 pm
Location: North West UK
Blog: View Blog (1)


Re: Multiline variable in python

Post by nathandelane on Mon Jul 28, 2008 6:55 am
([msg=8514]see Re: Multiline variable in python[/msg])

If you have a "multiline" variable like
Code: Select all
a = "hello\nworld\nlinux\nrocks"

Then you can use Python's find method and substring ([start:count]) context to extract a particular portion:
Code: Select all
print s[0:s.find("\n")]

That will print
Code: Select all
hello

You could also find out how many of your delimiters (string separators) there are in your "mulitline" variable.
Code: Select all
s.count("\n")

Then ultimately you could also transform your "multiline" variable into an array using Python's split function
Code: Select all
arr = s.split("\n")

Then you could use a loop to go through those. Here is a site with some good references on it for Python. You can see the definitions for each of those methods, like the find method, int find(sub [,start[,end]]), for example.

I hope that helps a little bit.
Me, Nathandelane, Highly influential to Hackerdom, Premature Optimization=http://c2.com/cgi/wiki?PrematureOptimization
User avatar
nathandelane
Poster
Poster
 
Posts: 204
Joined: Thu Jun 26, 2008 11:26 am
Location: Utah
Blog: View Blog (0)


Re: Multiline variable in python

Post by thedotmaster on Mon Jul 28, 2008 1:36 pm
([msg=8559]see Re: Multiline variable in python[/msg])

Thanks loads! That's saved me a hell of a lot of time!
To a mod: lock thread. Answer has been found.
Cheers again.
Image
User avatar
thedotmaster
Contributor
Contributor
 
Posts: 984
Joined: Sun May 04, 2008 4:39 pm
Location: North West UK
Blog: View Blog (1)


Re: [solved] Multiline variable in python

Post by ScrAm on Sat Aug 02, 2008 11:20 pm
([msg=8729]see Re: [solved] Multiline variable in python[/msg])

Locked.
ScrAm
Experienced User
Experienced User
 
Posts: 92
Joined: Sun Apr 13, 2008 3:17 pm
Location: Indiana
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests