Page 1 of 1

Snippet of Parsing

Posted: Mon Mar 10, 2014 8:46 pm
by lilzz
scriptname = scriptfile.split("/")[-1].split(".")[0]

what does that above does?
any example for that?

Re: Snippet of Parsing

Posted: Mon Mar 10, 2014 8:49 pm
by croston
It strips off the pathname and file extension from a filename to give the script name.

Re: Snippet of Parsing

Posted: Mon Mar 10, 2014 8:51 pm
by DougieLawson
http://docs.python.org/2/library/stdtyp ... #str.split

Looks like it will split /dir/subdir/subsubdir/file.name
into scriptname== "file"
dropping all of the other parts of the filename and directory names.

Re: Snippet of Parsing

Posted: Mon Mar 10, 2014 8:53 pm
by lilzz
DougieLawson wrote:http://docs.python.org/2/library/stdtyp ... #str.split

Looks like it will split /dir/subdir/subsubdir/file.name
into scriptname[0] == "dir", scriptname[1] == "subdir", scriptname[2] == "subsubdir" and scriptname[3] = "file.name"

what about those [-1] and [0] things? I am not too clear on that.

Re: Snippet of Parsing

Posted: Mon Mar 10, 2014 8:55 pm
by DougieLawson
lilzz wrote:
DougieLawson wrote:http://docs.python.org/2/library/stdtyp ... #str.split

Looks like it will split /dir/subdir/subsubdir/file.name
into scriptname[0] == "dir", scriptname[1] == "subdir", scriptname[2] == "subsubdir" and scriptname[3] = "file.name"

what about those [-1] and [0] things? I am not too clear on that.
Why not try it.

Code: Select all

pi@pi ~ $ python
Python 2.7.6 (default, Feb 28 2014, 07:43:05)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> script = "/home/pi/foo/bar.file"
>>> scriptname = script.split("/")[-1].split(".")[0]
>>> print scriptname
bar
>>> print scriptname[0]
b
>>> print scriptname[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> print scriptname[1]
a
>>>

Re: Snippet of Parsing

Posted: Mon Mar 10, 2014 8:57 pm
by croston
[-1] is the last item in a list, [0] is the first item in a list.