Select to view content in your preferred language

Is there a way to remove a specific character from a string in ArcGIS

3986
13
03-06-2018 02:31 AM
Adil_Toorawa
Emerging Contributor

Hi,

I have a list as follows;

Object ID        Field 1

1                     Example,Example

2                     ,Example,Example,Example

3                     ,Example

I want to remove just the first comma.

I would appreciate your assistance.

13 Replies
DanPatterson_Retired
MVP Emeritus

lots of ways, but a simple code block might do it

# ---- code block
def func(a):
    if a[0] == ',':
        return a[1:]
    else:
        return a

# --- 'a' is your field name with the python parser, the expression would be
#      func(!YourFieldNameHere!


a = 'Example,Example'

a
'Example,Example'

b = ',Example,Example,Example'

func(b)
'Example,Example,Example'
Adil_Toorawa
Emerging Contributor

Hi Dan, thanks for this however it doesn't seem to work. I replaced 'a' with my field name. I am using field calculator. Do i have to add anything in codeblock? 

0 Kudos
DanPatterson_Retired
MVP Emeritus

Set the field calculator to following for the second example

  • python parser
  • make sure that you have activated your new field ie 'newfield
  • !fieldnamehere! is the name of the old field containing the data
  • [!fieldnamehere!, !fieldnamehere![1:]][!fieldnamehere![0] == ',']

And if you are getting an error, then show it.

As for the code block, nothing needs to be changed, but your expression box would call the function with

func(!fieldnamehere!)

Of course, python parser and you are calculating values in a new text field.

Adil_Toorawa
Emerging Contributor

Done it. Thanks.

DanPatterson_Retired
MVP Emeritus

Adil... perhaps you could mark the thread Answered with the one that provided you the answer so others know a solution was reached and what one was used

DanPatterson_Retired
MVP Emeritus

Or more simply as a straight field calculation... python parser

replace 'a' with your field name in exclamation marks as above

a = ',Example,Example,Example'

[a, a[1:]][a[0] == ',']
Out[27]: 'Example,Example,Example'
XanderBakker
Esri Esteemed Contributor

In  case you have multiple commas at the start you could use this function in the code block:

def EliminateStartignCommas(txt):
    while txt[0] == ',':
        txt = txt[1:]
    return txt
PeteCrosier
Frequent Contributor

You could also use txt.lstrip(",")

JoeBorgione
MVP Emeritus

And just to play devils advocate....  What about a find and replace for " , "  at the start of the field?

That should just about do it....