I am creating a model which will give me two string values, one which reads exactly what is in a field and another which automatically replaces any Space with an "_". I have used Calculate Value tool, and entered in the following:
Expression:
ReplaceName(%Value%)
Code Block:
def ReplaceName(name):
return name.replace(" ", "_")
The result is an error:
ERROR 000539: Error running expression: ReplaceName(NoSpace1)
Traceback (most recent call last):
File "<expression>", line 1, in <module>
NameError: name 'NoSpace1' is not defined
I suspect because not all my Values have spaces
How can I make this work?
3 Answers 3
You don't necessarily have to define a function for this one. Try this:
str(!PlaceName!).replace(' ', '')
The "not defined" error is related to the lack of quotes around the NoSpace1. This could be from the % on either side of the Value. Your expression should be
ReplaceName(!Placename!)
-
or
str(!PlaceName!).replace(' ', '_')
for underscores2016年04月18日 18:17:53 +00:00Commented Apr 18, 2016 at 18:17 -
Thanks for your answer! however it didn't work! I tried several variations including the example you gave. Executing (Calculate Value): CalculateValue str(!PlaceName!).replace(" ", "") # String ERROR 000539: SyntaxError: invalid syntax (<expression>, line 1) Executing (Calculate Value): CalculateValue str(!Value!).replace(" ", "") # String ERROR 000539: SyntaxError: invalid syntax (<expression>, line 1)E. Ballent– E. Ballent2016年04月18日 18:40:00 +00:00Commented Apr 18, 2016 at 18:40
-
Try double clicking the field name to put it in the expression; sometimes a dataset will have a field name prefix that doesn't show up in the attribute table. Also try changing the double quotes to single quotes. Also for the parser make sure you're using the PYTHON_9.3 option. Is the field calculator returning any values at all?crld– crld2016年04月18日 20:41:30 +00:00Commented Apr 18, 2016 at 20:41
You do not need the field calculator for replace at all.
You can just use the Find & Replace tool which is accessed from the attribute-table which has the search/replace function the same way as in Excel, for example.
It also works for all columns simultaneously or can be set to search for whole values etc.
-
Thanks for your answer, but I need this to work inside of model builder, also I am not trying to change the value in the table. Ultimately both the value with the space and the value without a space are going to be used as inputs in a later portion of the model.E. Ballent– E. Ballent2016年04月19日 13:12:33 +00:00Commented Apr 19, 2016 at 13:12
This may not be the most elegant of fixes, but it did work:
I found that the %Value% had to have Quotes and I used a try/except sequence to get around the possible lack of a space in some of the values.
Explore related questions
See similar questions with these tags.