This method seems a little dangerous as I can envision where the string "0a" could occur in your hex string by accident, for example the two byte hex "b0 ac" represented this way would be an invalid match.
Here's a function implementation of your approach, not using hex codes. You could paste this function into the ArcMap python window and use it there. Note I'm using chr(10) and chr(13) for "\n" and "\r" so this function can also be used inside the Calculate Value tool in modelbuilder... as the usual use of "\n" breaks the geoprocessing messaging string representation in the code...
I'm also using arcpy.da.UpdateCursor because it is very fast compared to the 10.0 flavor.... and the "with" construct helps you out by closing the cursor even if the code fails -- avoiding the possibility of a nasty hanging file lock!
import arcpy def strip_newlines(tbl, field, eolchar=""): with arcpy.da.UpdateCursor(tbl, [field]) as rows: for row in rows: row[0] = row[0].replace(chr(10), eolchar).replace(chr(13), eolchar) rows.updateRow(row)
This worked for me in 10.2. For some reason the old methods that worked in 10.0 no longer worked in 10.2 so I'm glad I found your solution Curtis. Thanks for sharing!
This is the solution that worked for me, though I removed the len(row.NAME) >= 255 requirement.
Here's the working example:
rows = arcpy.UpdateCursor("Assets\Welds") for row in rows: hexString = str(row.REMARKS).encode("hex") if "0a" in hexString: hexString = hexString.replace("0a","") row.REMARKS = hexString.decode("hex") rows.updateRow(row)
Replace "Assets\Welds" with the appropriate fc name and replace row.REMARKS with row.(insert field name here)
You may or may not need to run:
import arcpy import string
I just wanted to make this idiotproof because I struggled for a bit (I copied and pasted your example expecting it to work). I'm still somewhat new to (and still learning) Python so I'm sure I'm not the only one who will forget to change the appropriate variables to their ArcGIS data.
Why does the field calculator for Python reject standard strings with \t , \n, etc. characters? What is the point of castrating Python's string operators?
Could you paste the actual working code you used to get the example working properly?
import os import arcpy tbl = arcpy.CreateScratchName("","","table","in_memory") arcpy.CreateTable_management("in_memory",os.path.basename(tbl)) arcpy.AddField_management(tbl,"TESTFIELD","TEXT") Rows = arcpy.InsertCursor(tbl) Row = Rows.newRow() Rows.insertRow(Row) del Row, Rows arcpy.CalculateField_management(tbl,"TESTFIELD","chr(10) + chr(13)","PYTHON_9.3") print arcpy.GetMessages() Rows = arcpy.SearchCursor(tbl) Row = Rows.next() print "Field value: ",repr(Row.TESTFIELD) del Row, Rows
Executing: CalculateField in_memory\xx0 TESTFIELD "chr(10) + chr(13)" PYTHON_9.3 # Start Time: Mon Aug 05 10:49:33 2013 Succeeded at Mon Aug 05 10:49:33 2013 (Elapsed Time: 0.00 seconds) Field value: u'\n\r'
The problem is that you cannot use Python escape codes like "\r" in the Field Calculator code block or the Calculate Value code block. I'm assuming this has something to do with the parsing of python arguments into string representation in the arcpy/gp messaging framework.If you need to access escape characters, use the chr() function instead. This will probably work fine:rows = arcpy.UpdateCursor(fc) for row in rows: newline = chr(13) + chr(10) if newline in row.TextString: row.setValue('TextString', row.TextString.replace(newline, ' ')) rows.updateRow(row) del row del rows
rows = arcpy.UpdateCursor(fc) for row in rows: newline = chr(13) + chr(10) if newline in row.TextString: row.setValue('TextString', row.TextString.replace(newline, ' ')) rows.updateRow(row) del row del rows
However, if I go from the console and set up something like: rows = arcpy.UpdateCursor(fc) for row in rows: if '' in row.TextString: row.setValue('TextString', row.TextString.replace('', ' ')) rows.updateRow(row) del row, rows It works exactly as one would expect. But I would love to know more about why this doesn't seem to work from the Field Calculator window.
rows = arcpy.UpdateCursor(fc) for row in rows: if '' in row.TextString: row.setValue('TextString', row.TextString.replace('', ' ')) rows.updateRow(row) del row, rows
rows = arcpy.UpdateCursor(fc) for row in rows: newline = chr(13) + chr(10) if newline in row.TextString: row.setValue('TextString', row.TextString.replace(newline, ' ')) rows.updateRow(row) del row, rows
rows = arcpy.UpdateCursor(fc) for row in rows: if '' in row.TextString: row.setValue('TextString', row.TextString.replace('', ' ')) rows.updateRow(row) del row del rows
I ran into the same problem when using python to add hyperlinks. As hyperlinks contain "\" characters it sometimes happened that a "\n" was in the hyperlink. I solved it by passing in the hyperlink as a raw string instead of a normal string:hyperlink = "c:\somehyperlink\name_of_file" arcpy.CalculateField_management(TableToEdit, "HYPERLINK_FIELD", r"r'" + hyperlink + r"'", "PYTHON")
hyperlink = "c:\somehyperlink\name_of_file" arcpy.CalculateField_management(TableToEdit, "HYPERLINK_FIELD", r"r'" + hyperlink + r"'", "PYTHON")
>>> print "c:\somehyperlink\name_of_file" c:\somehyperlink ame_of_file
>>> print 'r"{0}"'.format(r"c:\somehyperlink\name_of_file") r"c:\somehyperlink\name_of_file"
hyperlink = r"c:\somehyperlink\name_of_file" arcpy.CalculateField_management(TableToEdit, "HYPERLINK_FIELD", '{0}"'.format(hyperlink), "PYTHON")
def msg(): # text = "\n\nThis is\na message to you.\n" # does not work text = "{0}{0}This is{0}a message to you.{0}".format(chr(10)) return text
3) Nick's hexidecimal conversion seems to work for \n but, again, how can we apply it to other special characters? Or is it just easier to use VB instead of Python for field calculations?
Or is it just easier to use VB instead of Python for field calculations?
rows = arcpy.UpdateCursor(fc) for row in rows: if len(row.NAME) >= 255: hexString = str(row.NAME).encode("hex") if "0a" in hexString: # "0a" is hex equivalent of '\n' hexString = hexString.replace("0a","") row.NAME = hexString.decode("hex") rows.updateRow(row)
>>> x 'here is my real text\n' >>> x.strip() 'here is my real text'
arcpy.CalculateField_management(mytable,"FIELDNAME","!FIELDNAME!.strip()","PYTHON")
arcpy.CalculateField_management(mytable,"FIELDNAME","Trim([FIELDNAME]")
Try dumping the table to a text file, if you think there is stuff going on in there you cannot see.There is an 're' module in python that handles regular expressions. That is the tool set you want for weeding out pesky newlines ('\n').It may be easier to weed them in the table or in the text dump (which could then be re-imported to a table).
#ESRI Codeblock codeblock="""def trimNewline(val): import re newVal = re.sub('(?m)[]',"",val) return newVal""" #Expression parameter expression = "trimNewline(str(!FIELD!)) # CalculateField_management(in_table,field,expression,{expression_type},{code_block}) arcpy.CalculateField_management(mytable,"FIELDNAME",expression,"PYTHON",codeblock)
Los miembros registrados pueden publicar, seguir actualizaciones y más. ¿Nuevo aquí? Regístrate gratis.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.