Hi, I have a text string "1.03 ac @@ $2,246/ac = 2,253.29" and would like to separate out the bold portion into a separate field. Can I do this in field calculator?
Thanks,
Michael Kohler
Solved! Go to Solution.
s = "1.03 ac @@ $2,246/ac = 2,253.29"
float(s.split(" ")[-1].replace(",",""))
s = "1.03 ac @@ $2,246/ac = 2,253.29"
float(s.split(" ")[-1].replace(",",""))
2253.29
#
# shorter number
s = "1.03 ac @@ $2,246/ac = 253.29"
float(s.split(" ")[-1].replace(",",""))
253.29assuming the number is always the last and the number is comma delimited.
's' is your field name of course
destination field needs to be "double" aka float
source field is text see attached since I can't insert the image here for some reason
s = "1.03 ac @@ $2,246/ac = 2,253.29"
float(s.split(" ")[-1].replace(",",""))
s = "1.03 ac @@ $2,246/ac = 2,253.29"
float(s.split(" ")[-1].replace(",",""))
2253.29
#
# shorter number
s = "1.03 ac @@ $2,246/ac = 253.29"
float(s.split(" ")[-1].replace(",",""))
253.29assuming the number is always the last and the number is comma delimited.
's' is your field name of course
Thanks!
Hi Dan, when I entered the code as you wrote it, it works. But when I enter the field name, I get and error. If my field name is "Notes" do I enter the expression as:
float(!Notes!.split("$")[-1].replace(",",""))
The following is possibly overkill for your situation, but regular expression is the hammer I like to use on everything like a nail. 🙂
The following uses regex to extract all three numerical values in the text string, and then return one of them based on how the custom function is called. If the string field is NULL then NULL is returned.
Expression Type:
PYTHON3
Expression:
extract_value(!text_field!, "total")
Code Block:
import re
pattern = re.compile(
r"(?P<acre>[\d,.]+)\s*ac\s*@@\s*\$"
r"(?P<price>[\d,.]+)/ac\s*=\s*"
r"(?P<total>[\d,.]+)"
)
def extract_value(field, value):
if field is not None:
match = re.search(pattern, field)
return match.groupdict()[value]