Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip the string which contain forward slash?

Tags:

python

i am new to python programming,trying to strip the string which contains forward slash character,i expected output as '/stack' but giving result as below. Could you help me how can i achieve expected output.Is there any other easy way to achieve the same.

>>> name='/stack/overflow'
>>> sub ='/overflow'
>>> name.strip(sub)
'stack'

Thanks in advance hema

like image 829
user1559873 Avatar asked Oct 24 '13 17:10

user1559873


People also ask

How do you remove the last slash from a string in Java?

replaceAll("/","");

How do you use forward slash to separate words?

To Separate And From Or (And/Or)Forward slashes are also used to separate the words "and" and "or" (and/or) when they are used side by side in writing. This is much easier for readers to understand than the alternative, which would require writing the word "and" two times in a row.


2 Answers

The .strip method doesn't do what you think it does:

Docstring:
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

So what you're doing is saying "remove /,o,v,e,r,f,l,o, and w from the beginning or end of this string."

Instead, try splitting on /, taking all but the last element, and rejoining:

In [12]: '/'.join("/stack/overflow".split('/')[:-1])
Out[12]: '/stack'

If you actually just want to remove the substring '/overflow', you can do:

In [15]: "/stack/overflow".replace('/overflow', '')
Out[15]: '/stack'
like image 123
Christian Ternus Avatar answered Sep 30 '22 22:09

Christian Ternus


First you need to check which OS you are using,

if its Linux/Unix

normally the file path is denoted by /

so you can simply use,

>>>name = '/stack/overflow'

>>>name.split(os.sep)  # Here os.sep is nothing but "/"

['', 'stack', 'overflow']

if it's windows,

just use

>>> name.split("/")
['', 'stack', 'overflow']
like image 28
Siva Cn Avatar answered Sep 30 '22 22:09

Siva Cn