String Manipulation

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Wed Jul 16 00:28:19 CEST 2003


John Hunter wrote:

>>>>>>"lamar" == lamar air <lamar_air at hotmail.com> writes:
> 
> 
>     lamar> I need a piece of code that takes a string like this
>     lamar> string1 = "aaa/bbb/ccc/dd" and extracts a string
>     lamar> containting the character after the last "/"
> 
> One good way to do this is to split the string on the '/' character,
> which creates a list of strings
> 
>   >>> string1 = "aaa/bbb/ccc/dd"
>   >>> parts = string1.split('/')
>   >>> parts
>   ['aaa', 'bbb', 'ccc', 'dd']
> 
> Now you just want to get the last element of this list; python allows
> you to index with -1 to get the last element, -2 to get the second to
> last, etc...
> 
>   >>> parts[-1]
>   'dd'
> 
> JDH
> 

While is is perfectly acceptable, you might want to consider another
solution if it is *path names* you are manipulating:

 >>> import os
 >>> os.path.split("aaa/bbb/ccc/dd")
('aaa/bbb/ccc', 'dd')
 >>> os.path.split("aaa/bbb/ccc/dd")[1]
'dd'


because this will work correctly on other platforms too when the
path separator is not '/'.

--Irmen de JOng





More information about the Python-list mailing list