15

I am trying to replace newline characters in a unicode string and seem to be missing some magic codes.

My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a db.StringProperty() in my model.

So I do something like:

link.title = unicode(page_title,"utf-8").replace('\n','').replace('\r','')

and I get:

Property title is not multi-line

Are there other codes I should be using for the replace?

1
  • Print the repr() of page_title and see which special characters it contains. Feb 4, 2010 at 17:25

3 Answers 3

22

Try ''.join(unicode(page_title, 'utf-8').splitlines()). splitlines() should let the standard library take care of all the possible crazy Unicode line breaks, and then you just join them all back together with the empty string to get a single-line version.

0
11

Python uses these characters for splitting in unicode.splitlines():

  • U+000A LINE FEED (\n)
  • U+000D CARRIAGE RETURN (\r)
  • U+001C FILE SEPARATOR
  • U+001D GROUP SEPARATOR
  • U+001E RECORD SEPARATOR
  • U+0085 NEXT LINE
  • U+2028 LINE SEPARATOR
  • U+2029 PARAGRAPH SEPARATOR

As Hank says, using splitlines() will let Python take care of all of the details for you, but if you need to do it manually, then this should be the complete list.

2
  • That is helpful. But looks like splitlines() did it for me. Feb 4, 2010 at 19:30
  • No worries; I figured splitlines() was the right answer; This was just in case you really needed the list. Feb 5, 2010 at 17:45
0

It would be useful to print the repr() of the page_title that is seen to be multiline, but the obvious candidate would be '\r'.

1
  • I updated my example to include the carriage return (same result). Feb 4, 2010 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.