Converting a VB script into Python

3133
11
Jump to solution
10-24-2019 08:29 AM
SLouq
by
Occasional Contributor III

I had some VB code in one of my Calculate Field modules in modelbuilder. I am trying to convert it to Python
Can anybody help me with this?

IF RTRIM([PRE_DIR]) = " " then

MyLabel = LTRIM([STR_NAME]) & " " & [SUF_FIX]

else

MyLabel = RTRIM([PRE_DIR]) & " " & LTRIM(RTRIM([STR_NAME])) & " " & [SUF_FIX]

end If

Thanks

0 Kudos
1 Solution

Accepted Solutions
RobertBorchert
Frequent Contributor III

If you have it in model builder simply open it in model builder.

Then under Model and Export you can export it automatically to a python scrip.

View solution in original post

0 Kudos
11 Replies
RobertBorchert
Frequent Contributor III

If you have it in model builder simply open it in model builder.

Then under Model and Export you can export it automatically to a python scrip.

0 Kudos
SLouq
by
Occasional Contributor III

Thanks Robert! I knew there was an easy way to do this. HAHA!

0 Kudos
SLouq
by
Occasional Contributor III

I know I marked your response as correct and it may be correct but I'm still getting an error when trying to convert my if statement to python. I tried this but it isn't working

If (!PRE_DIR!).RTrim() = " "

   print(!STR_NAM!) + " " + (!SUF_FIX!)

else

   print(!PRE_DIR!).RTrim() + " " + LTrim (RTrim(!STR_NAME!)) + " " +

Return !SUF_FIX!

Any help would be appreciated!

Thanks

0 Kudos
RobertBorchert
Frequent Contributor III

Whatever your trying to convert it does not look like it came from Model Builder. 

I have used VB code in model builder expressions in the past and if they work in model builder, which I am assuming yours do, they should convert to python and the code from your last post is not python.  Or are you just posting the original VB code.

0 Kudos
SLouq
by
Occasional Contributor III

I know I have the syntax wrong because I am very unfamiliar with python syntax. I have just been looking at python examples on the internet and doing what I thought would work since what I had in VB works. Here is a screenshot of the Calculate Field module I have in python.

Calculate Field module

0 Kudos
RobertBorchert
Frequent Contributor III

What does the syntax look like when you open the python script after you export it as python

0 Kudos
SLouq
by
Occasional Contributor III

# Process: Calculate Field (2)
arcpy.CalculateField_management(clines__5_, "LABEL", "RTRIM([PRE_DIR]) & \" \" & LTRIM(RTRIM([STR_NAME])) & \" \" & [SUF_FIX]", "VB", "IF RTRIM([PRE_DIR]) = \" \" then\\n    MyLabel = LTRIM([STR_NAME]) & \" \" & [SUF_FIX]\\nelse\\n

0 Kudos
RobertBorchert
Frequent Contributor III

That looks like it should work when you run the python script. 

0 Kudos
SLouq
by
Occasional Contributor III

Then I just need to learn how to enter it into the prelogic part of the module.

Thank you for helping me figure out this issue Robert!

0 Kudos