I need to strip leading and trailing whitespace, split string into list to remove excess whitespace between words and uppercase all values within one Python code block and calculation in Pro field calculator. I have the following code block started (below). I'm trying to identify the best way to account for all these stored variables before return of the final string value.
address =
fieldcalc(!address!)
def fieldcalc(address):
str1 = address.upper()
str2 = address.strip()
str3 = address.split(" ")
finalstr = ???
return finalstr
Example bad string value: " String is fixed " Final String Value: "STRING IS FIXED"
-
It is always good to give some examples so people can validate whether they understand your question correctly.bixb0012– bixb00122023年02月08日 21:47:24 +00:00Commented Feb 8, 2023 at 21:47
-
Why are you making all those extra variables and not using them?Vince– Vince2023年02月09日 03:06:22 +00:00Commented Feb 9, 2023 at 3:06
2 Answers 2
Not sure I understand the question completely, i.e., all edge cases depending on data, but the following should/might work in the expression box (no need for creating function):
" ".join(s.upper() for s in !address!.split(" ") if s)
-
I don't see .strip() used here? And I need to use .upper(), not .title(), correct?J56– J562023年02月08日 21:56:50 +00:00Commented Feb 8, 2023 at 21:56
-
You don't need
str.strip
because the combination of splitting the string based on spaces and using a generator expression with a conditionif s
drops all the empty spaces. And yes, you can changes.title()
tos.upper()
. I will update the code sample.bixb0012– bixb00122023年02月08日 22:44:21 +00:00Commented Feb 8, 2023 at 22:44
Another solution to remove excess white space is to use strip/join in combination with str/or '' for any fields that might have null (None) values. For example:
' '.join((!Address_Number! + ' ' + str(!Road_Prefix_Dir! or '') + ' ' + !Road_Name! + ' ' + !Road_Type!.title() + ' ' + str(!Road_Post_Dir! or '') + ' ' + str(!Unit_Type!.title() or '') + ' ' + str(!Unit_Number! or '')).split())
This allows flexibility for each field, such as using the title function in the example above. This is a good workaround to avoid the "None" error in the field calculator when using string functions with fields that may have null values instead of blanks.
Thanks and kudos to the link below for help with the str/or '' workaround. https://www.geeksforgeeks.org/python-convert-none-to-empty-string/
Explore related questions
See similar questions with these tags.