0

I am making a application where I am using some auto generate regular expressions which are multi line is the reg Ex string contains \n.

Now every time i execute a generate command i would like to print the command to console also for documentation ect.

INFO: Command execute: (regular expression) 

however if i just print my Reg Ex string containing the \n I also get newline in the printout which is not desirable.

INFO: Command execute: (regular expre ssion) 

I can get it to print the newline \n by adding an escape char making it \\n and it is also how it looks on the print out.

INFO: Command execute: (regular expre\\nssion) 

This is not desirable either. What I am looking for is to be able to print it like following.

INFO: Command execute: (regular expre\nssion) 

Is this possible ?

regards

2
  • How exactly are you "printing" this? print('regular expre\\nssion') prints 'regular expre\nssion' on my computer Commented Oct 25, 2015 at 13:14
  • @Markus Well its a slight more complicated than that, first i use re.escape(my_str) to make a fully valid regular expression compatible string. The i compile it and print it using print(compiledStr.pattern) . However I found that the pattern string was \\\n and that was why it wasnt not working. i replace the \\\n with \\n and i get your result. Commented Oct 26, 2015 at 15:49

2 Answers 2

3

Use the built-in function repr() to get the string that would reproduce that object when evaluated:

>>> text = 'INFO: Command execute: (regular expre\nssion)' >>> print(text) INFO: Command execute: (regular expre ssion) >>> print(repr(text)) 'INFO: Command execute: (regular expre\nssion)' 
Sign up to request clarification or add additional context in comments.

Comments

2

You can try this. String prefix r makes it ignore all escapes.

a = r"Hello\nworld" print a # Hello\nworld 

If you still need new lines while using r, you can use triple quote sintax

b = r"""Big \n long \n string""" print b # Big \n long # \n # string 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.