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
replaceAll("/","");
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.
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'
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With