ID | Sent Phone | Length | New Phone |
1 | 3 | 1 | 0 |
2 | 22 | 2 | 0 |
3 | 213 | 3 | 0 |
4 | 1 | 1 | 0 |
5 | 33445678 | 8 | 33445678 |
6 | 11 | 2 | 0 |
7 | 2 | 1 | 0 |
8 | 12569826 | 8 | 12569826 |
9 | 12560912 | 8 | 12560912 |
10 | 34235677 | 8 | 34235677 |
Solved! Go to Solution.
code:
func(!Sent Phone!)
pre-logic script:
# only works for a string, add some
#logic to test for str, int float etc
#then if/else it in a similar block
def func(input):
if len(input) == 8:
result = input
else:
result = '0'
return result
In your illustration, have you updated the Length field already, or is that to be part of the script?
My first thought is to use an update cursor with arcpy or do you want to keep this at the field calculator level?
In your illustration, have you updated the Length field already, or is that to be part of the script?
My first thought is to use an update cursor with arcpy or do you want to keep this at the field calculator level?
R// I would like to keep it from the field calculator
code:
func(!Sent Phone!)
pre-logic script:
# only works for a string, add some
#logic to test for str, int float etc
#then if/else it in a similar block
def func(input):
if len(input) == 8:
result = input
else:
result = '0'
return result
In addition to David's answer, this can be accomplished with a one-liner in the expression block that doesn't require a pre-calculated length field:
!Sent Phone! if len(!Sent Phone!) == 8 else '0'
on looking back at my answer I'm also missing quotes to make 0 a string. Have edited or will try if able. Loving the one liner Joshua!
Sharing the full error message would be helpful
Executing (Calculate Field): CalculateField "C:\Users\Shp_salida\001.shp"
Phone func( !Telefono_C! ) PYTHON_9.3 "def func(input):\n if len(input) == 8:\n result = input\n else:\n result = 0\n return result\n"
Start Time: Thu May 21 15:59:34 2020
ERROR 000539: Error running expression: func( 5 )
Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 2, in func
TypeError: object of type 'int' has no len()
Failed to execute (Calculate Field).
Failed at Thu May 21 15:59:34 2020 (Elapsed Time: 0.01 seconds)
Failed to execute (Model72).
Failed at Thu May 21 15:59:34 2020 (Elapsed Time: 1.34 seconds)
Ok so an integer is being passed into the function. Replace if len(input) with if len(str(input))