2

I am doing a little test to grab backslash (\) using Python regex and what I found is a bit strange.

import re
stringing = "\\"
pattern = re.compile(r'(\\)')
search = pattern.search(string)
print search.group()

The output is shown below, which is as expected

\

However, when I use .groups() as,

print search.groups()

I get

('\\',)

Which is clearly wrong. Not sure what is happening.

enter image description here

5
  • try search.group() alone without print. It will give you '\\' not a backslash. Commented Mar 5, 2015 at 3:33
  • Yes it does. Why is that though? Isn't it supposed to give only one `\` Commented Mar 5, 2015 at 3:36
  • i think it's because of the ide you're running. Commented Mar 5, 2015 at 3:37
  • try this for i in re.search(r'(\\)', s).groups(): print i Commented Mar 5, 2015 at 3:38
  • @AvinashRaj I am running in a Python interpreter opened inside a linux terminal. Commented Mar 5, 2015 at 3:41

1 Answer 1

4

tl;dr \ is the str representation of the backslash character and '\\' is the repr representation of the backslash character.

In this case, search.group returns a string. The actual string representation of \ is \ only. But, when you print a tuple, it internally calls the repr on all the objects in it. The result of repr on \ is '\\'.

You can check that like this

print repr(search.group()), str(search.group())
# '\\' \
Sign up to request clarification or add additional context in comments.

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.