0

I am trying to strip a prefix from a string, e.g. turn

VTK/Examples/Test

Into

Test

Sometimes the string does not contain the prefix, in which case I would expect nothing to happen. However,

>>> S="Main Page"
>>> S.strip("VTK/Examples/")
'Main Pag'

You can see that the 'e' on the end of "Main Page" has been removed.

I even tried to escape the slashes

>>> S.strip("VTK\/Examples\/")
'Main Pag'

but it still strips the 'e'. Can anyone explain this behavior?

Thanks,

Dave

3
Contributors
5
Replies
7
Views
6 Years
Discussion Span
Last Post by woooee
Featured Replies
  • 1

    Strip removes all those letter which are in the argument out from the string object. Because you are only stripping '//EKTV\\\\a[B]e[/B]lmpsx' the other letters are not stripped. (\ is double, but it does not matter to strip.) [CODE]import os path='VTK/Examples/Test' ## let's use properly the directory separator from os.path pathlist=path.split(os.path.altsep) … Read More

1

Strip removes all those letter which are in the argument out from the string object.

Because you are only stripping '//EKTV\\\\aelmpsx' the other letters are not stripped. (\ is double, but it does not matter to strip.)

import os
path='VTK/Examples/Test'
## let's use properly the directory separator from os.path
pathlist=path.split(os.path.altsep)
print pathlist[-1]
""" Output:
>>> 
Test
>>> 
"""

Edited by pyTony: n/a

Comments
Thanks for pointing me in the right direction!
0

That didn't work right out of the box (why would the index be -1?) but it got me closer to the solution:

MyString = "VTK/Examples/Test"
PathSplit = os.path.split(MyString)
PathName = PathSplit[0]
ExampleName = PathSplit[1]

However, what I'm really trying to do is get the string that comes after "VTK/Examples/" even if there is more of a path, i.e. if the string is

VTK/Examples/IO/Python/Test

I want to know that yes, it is in VTK/Examples, and then that it's path is IO/Python/Test

Can os.path do something like this?

Thanks!

Dave

Edited by daviddoria: n/a

0

MyList[-1] is the last thing in the list.

This new request is not more difficult:

## more simple splitting

MyString='VTK/Examples/IO/Python/Test'

## we do not care what is before the partition so assign them to _
_,found,want_this=MyString.partition('VTK/Examples/')

if found: print want_this ## found is 'VTK/Examples/', the looked thing


MyString='VK/Examples/IO/VTK/Test'

## we do not care what is before the partition so assign them to _
_,found,want_this=MyString.partition('VTK/Examples/') ## found is empty

if found: print want_this
0

To find a sub-string within a string, find a sub_string within a string.

st = "VTK/Examples/Test"
to_find = "VTK/Examples/"
start = st.find(to_find)
if start > -1:
    print st[start+len(to_find):]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.