Remove Newline Character Python – Removing Return/Newline Character from Field Using Python

arcgis-10.0arcgis-desktoperror-000539field-calculatorpython-parser

I have a geodatabase table with a field that I'm trying to remove return characters (new line). I found this post (How can I remove (chomp) a newline in Python?) of how to do it, however it is not working within field calculator. Here are the code snippets that I tried:
Note return character is not at the end of the string.

!myField!.rstrip()

OR

!myField!.rstrip('\n')

OR

!myField!.rstrip('\r\n')

OR

!myField!.replace('\n', '')

000539 error given for this option:

Description The calculation used by the Calculate Field or Calculate
Value tool is invalid. This error message provided will list the
specific Python error.

Solution This error code covers a number of Python errors:

Example error 1: exceptions.TypeError: cannot concatenate 'str' and
'int' objects. The above is a Python-specific error. The calculation
is attempting to add or concatenate a string and a number.

Example error 2: Invalid field shape@distance The above is an error
using the geometry object. The distance method is not a valid method
of the geometry object.

For specific Python issues, consult the external Python help for more
information, or consult the Calculate Field or Calculate Value help
for more information on these tools.

OR

import os
def removeReturn(myField):
  s = myField.rstrip(os.linesep)
  return s

Any ideas of how to remove return characters using field calculator?

Best Answer

I think this is just a bug/limitation of the Python parser with the field calculator/Calculate Field tool. If a newline is encountered within the text field, a SyntaxError: EOL while scanning string literal occurs no matter what you try.

I can reproduce the issue at 10.1 SP1 by importing the following CSV file into a file geodatabase, adding a field and simply attempting to copy the Text field to the new field using the Field Calculator with the Python parser and and the expression !Text!.

ID,Text
1,"this is a multiline 
example"

Try switching to the VB parser, or using an UpdateCursor and avoiding the Field Calculator entirely.

This issue is also discussed on the ESRI forums, with the same conclusions:

The only relevant NIM I could find was this:

  • NIM085499 - CalculateField calculations using non-ASCII characters fail on a Linux engine with: "ERROR 000539: SyntaxError: EOL while scanning string literal (, line 1)".