Javascript to Python

gbreed at cix.compulink.co.uk gbreed at cix.compulink.co.uk
Fri Mar 1 13:12:42 EST 2002


Sam Collett wrote:

> Does anyone know of any good sites on Javascript > Python examples?

Forgive me for being arrogant, but learning Python from the tutorial 
should tell you all you need.

> I have a function in javascript that returns the file extension:
> 
> function FileExtension(sFilePath)
> {
>     return Right(sFilePath,sFilePath.length-sFilePath.lastIndexOf("."))
> }
> 
> so FileExtension("/path/to/file.doc") would return .doc
> I would also want to return the filename (file) and the path
> (/path/to/). How would I go about that?

>>> import os
>>> os.path.splitext("/path/to/file.doc")[1]
'.doc'
>>> os.path.splitext(os.path.basename("/path/to/file.doc"))[0]
'file'
>>> os.path.dirname("/path/to/file.doc")
'/path/to'

> What equivalents to the functions Right and Left (right side of
> string, left side of string)

>>> "hello world"[:5]
'hello'
>>> "hello world"[-5:]
'world'

> Also is there an easier way to do number incrementing (just me being
> lazy):
> while r<5
>  print r
>  r=r+1
> 
> I have tried r++ to add 1 each time, and r-- to take away one, but
> this does not work, so is the only way r=r+1 or r=r-1 ?

Your code's missing a :  You can use r+=1 and r-=1 with recent enough 
versions of Python.  That particular example can be done

>>> for r in range(r, 5):
...     print r


                    Graham



More information about the Python-list mailing list