[Tutor] searching for newlines does not work!
adam.jtm30 at gmail.com
Sun Oct 24 00:09:35 CEST 2010
On 23/10/10 23:03, winder at interchange.ubc.ca wrote:
> This is driving me batty!
> In the interactive window, I can use string.replace on newlines for
> some strings and not for others.
> Here is what work for newlines:
> bill at bill-laptop:~$ python
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> test=r"a \n b \n c \n"
> >>> test.replace(r"\n","***")
> 'a *** b *** c ***'
> Yay! So far, so good. But now I put in a string with newlines, test2,
> using the triple quote method :
> >>> test2="""
> ... a
> ... b
> ... c
> ... """
> >>> test2.replace(r"\n","***")
> >>> test2
> Boo! It does not work. So there here is my question: Why does test
> work but test2 does not? (And: Why me?)
> Thanks for any suggestions,
The problem is your use of 'r' which means raw string. This means that
rather than /n meaning new line it literally means the character '/'
followed by the character 'n'.
In your first example you put the characters into the string test and
replaced the characters.
The second example you have actual newlines and are searching for the
characters "/n" which don't exist in your string.
More information about the Tutor