0

I have a string in python as below:

"\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"

I want to get the string as

"B1xxA1xxMdl1zzInoAEROzzMofIN"

I think this can be done using regex but could not achieve it yet. Please give me an idea.

6
  • Python 4?? is Python 4 here?? Commented Jan 6, 2012 at 7:55
  • Sorry, I updated the question. I meant python 2.4. Sorry again. Commented Jan 6, 2012 at 7:57
  • Do you mean you want to remove all the cars between the two backslashes \? Commented Jan 6, 2012 at 8:01
  • Yes. Including the back slashes. Thanks. Commented Jan 6, 2012 at 8:02
  • Why are you using Python 2.4? This is now nearly a decade old... Commented Jan 6, 2012 at 8:16

3 Answers 3

3
st = "\B1\B1xxA1xxMdl1zzInoAEROzzMofIN"
s = re.sub(r"\\","",st)
idx = s.rindex("B1")
print s[idx:]

output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'

OR

st = "\B1\B1xxA1xxMdl1zzInoAEROzzMofIN"
idx = st.rindex("\\")
print st[idx+1:]

output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'

Sign up to request clarification or add additional context in comments.

4 Comments

These look a bit too specific for me. What if the source is "123\\456\\789" - neither solution will give "123789" as a result.
his example was specific too, so i came with this specific solution. I thought he was facing problem with this specific string.
Thanks a lot RanRag. The second solution what I needed.
Note that this will work if you have only one double backslash. Yet, for this case, using list slicing is simple and efficient.
3

Here is a try:

import re
s = "\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"
s = re.sub(r"\\[^\\]+\\","", s)
print s

Tested on http://py-ide-online.appspot.com (couldn't find a way to share though)

[EDIT] For some explanation, have a look at the Python regex documentation page and the first comment of this SO question:

How to remove symbols from a string with Python?

because using brackets [] can be tricky (IMHO)

In this case, [^\\] means anything but two backslashes \\.

So [^\\]+ means one or more character that matches anything but two backslashes \\.

2 Comments

You make \w optional, and they may not be word chars, why not replace \w* with [^\\]+? You'd then have a general pattern
@fge: thanks for the suggestion, I've edited my answer with your code (it took me some time to check this as I am not that familiar to Python Regex)
0

If the desired section of the string is always on the RHS of a \ char then you could use:

string = "\\B1\\B1xxA1xxMdl1zzInoAEROzzMofIN"
string.rpartition("\\")[2]

output = 'B1xxA1xxMdl1zzInoAEROzzMofIN'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.