Remove extra spaces from string using the field calculator

16870
12
12-19-2011 07:14 AM
MattGoodman
New Contributor III
Hi, I'm looking for an elegant python expression that I can be used within ArcMap's field calculator to find all instances of consecutive spaces within a string and replace them with a single space.

Example:
[INDENT]Let's say in a field called "Address" we have the following value (the product of poor concatenation):[/INDENT]
[INDENT]"_123_____Main__St,____Townsville,______CA_98463___"[/INDENT]

[INDENT]It should become "123 Main St, Townsville, CA 98463"[/INDENT]


I know that .strip will get rid of the leading/trailling spaces.  How to I get a find/replace approach to continue looping through until all the double-spaces have been reduced to single spaces?  Also, I have tried using .split, but get an error in ArcMap that "Field is not Nullable".

Any help would be appreciated.
Tags (2)
0 Kudos
12 Replies
RichardFairhurst
MVP Honored Contributor
I know this is asking for a python method, but just in case it helps someone, the VB Script method to strip out all double spaces and any leading or trailing spaces is:

Output = [MyField] ' Replace MyField with the actual text field name
If Not IsNull(Output) then
  Output = Trim(Output)
  If Output > "" Then
    Do While InStr(1, Output, "  ")
      Output = Replace(Output, "  ", " ")
    Loop
  Else
    Output = " "  ' Avoid Field Is Not Nullable Error
  End If
Else
  Output = " "  ' Field allowed Nulls, use of this option replaces them with white space.
End If
0 Kudos
ChristopherMorneau
New Contributor II
fieldvalue=' '.join(fieldvalue.strip().split())
#in case fieldvalue=='', change empty string to space to avoid "Field is not Nullable" error
if not fieldvalue: fieldvalue=' '


I've been trying to set this up in the Field Calculator dialog, but I'm obviously missing something.  Thus far, all I've achieved is a syntax error message.

My situation is very similar to what Matt Goodman originally posted on 12-19-2011.  In my case, the field from which I want to remove extra spaces is entitled MailAddres.  What should I enter for the Expression & Pre-Logic Script Code fields to make this work?

Maybe a more fundamental question is: is there a Python equivalent to the TRIM(text) function found in MS Excel?

Thank you,

Christopher J. Morneau
0 Kudos
Luke_Pinner
MVP Regular Contributor
Create a function in the pre-logic script code block e.g.:
def trim(fieldvalue):
    fieldvalue=' '.join(fieldvalue.strip().split())
    # in case fieldvalue=='', change empty string to space 
    # to avoid "Field is not Nullable" error
    if not fieldvalue: fieldvalue=' '
    return fieldvalue


[ATTACH=CONFIG]29091[/ATTACH]