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

help on message splitting code

P: 15
Expand|Select|Wrap|Line Numbers
  1. filename = message.split()[1]  
  2.     f = open(filename[1:])  
  3.         outputdata = f.read()
what is the actual function of code here. first and second lines are hard to figure out :-/
Feb 12 '12 #1
Share this Question
Share on Google+
5 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
To begin with, the indentation is wrong.

message is a string object. String method split() is used to break the string into parts using whitespace as a delimiter.
Expand|Select|Wrap|Line Numbers
  1. >>> s = "A simple\tstring\nobject."
  2. >>> s
  3. 'A simple\tstring\nobject.'
  4. >>> print s
  5. A simple    string
  6. object.
  7. >>> s.split()
  8. ['A', 'simple', 'string', 'object.']
  9. >>> 
The code expects element 1 ('simple' in the example above) to be the name of a file object with an unwanted prefix character.
Expand|Select|Wrap|Line Numbers
  1. >>> fn = s.split()[1]
  2. >>> fn[1:]
  3. 'imple'
  4. >>> 
A file object is created with built-in function open() and read with file object method read().

Really, this is very basic Python. All this information is readily available in the Python documentation. A good place to start is python.org.
Feb 12 '12 #2

P: 15
i am familiar with split(),open() and read(). but my major concern is about the [1:].. i have neva come across such param with open(filename[1:]).

1.could u temme what [1:] signifies?
2.what is split function followed by [1] mean ?
Feb 12 '12 #3

bvdet
Expert Mod 2.5K+
P: 2,851
@akilasekaran
1. Elements of sequence types are accessed by the index operator (s[i]), slice operator (s[i:j]) and extended slice operator (s[i:j:stride]). Given a string "abcdef":
Expand|Select|Wrap|Line Numbers
  1. >>> "abcdef"[1:]
  2. 'bcdef'
  3. >>> "abcdef"[:1]
  4. 'a'
  5. >>> "abcdef"[1]
  6. 'b'
  7. >>> "abcdef"[0:5:2]
  8. 'ace'
  9. >>> 
2. String method split() returns a list. Index operator s[1] returns the element at index 1. Note the first element in a list is at index 0.
Feb 13 '12 #4

Expert 100+
P: 626

P: 15
oh wow i totally understood it.. thanks dwblas and bvdet :)
Feb 13 '12 #6

Post your reply

Sign in to post your reply or Sign up for a free account.