Shouldn't this return everything but the last word in the street name?
!Street_Name!.split(" ")[:-1]
Python parser is checked. Receiving nulls after calculation. If I try to slice[0], I get the first word. If I try to slice [-1] I get the last word. Why won't [:-1] return anything?
2 Answers 2
You probably need to join it back afterwards, otherwise you might be trying to calculate a field with a list:
" ".join('101 1st Street'.split(" ")[:-1])
As @faith_dur noted though, this will fail when there are no spaces in the string. A better way to do this would be with rsplit
:
for s in ['101 1st Street', '500 main street extension', 'NoSpacesHere']:
print(s.rsplit(' ', 1)[0])
Which prints:
101 1st
500 main street
NoSpacesHere
-
+1 Since the first code has an advantage over removing the extra spaces within the phrase and seems like
rsplit
is the elegant way of doing this instead of checking if the phrase is just one-word.fatih_dur– fatih_dur2016年12月02日 00:43:19 +00:00Commented Dec 2, 2016 at 0:43 -
@Paul That's odd because I'm making this selection prior to the calculation - Street_Name like ('% _') - so the records should all have at least one space and single final character. if there was a space at the end of a record it wouldn't be added to the selection. I there were no spaces then the select criteria (a space) between % and _ should exclude those records prior to the calculation attempt. I'll give your code a shot.geoJshaun– geoJshaun2016年12月02日 02:25:06 +00:00Commented Dec 2, 2016 at 2:25
Most probably there is/are white space(s) at the end of your strings. Try !Street_Name!.strip().split(" ")[:-1]
.
EDIT
I missed the colon in your slicing query. Please see below:
"xxxx yyyy".split(" ")[-1] returns--> yyyy
"xxxx yyyy".split(" ")[:-1] returns--> ['xxxx']
"xxxxyyyy".split(" ")[:-1] returns--> []
Basically, [:-1]
returns anything but the last slice ("xxxx yyyy zzzz".split()[:-1]
returns ['xxxx', 'yyyy']
) and if you have only one word in your street address, naturally it returns an empty list. I think you are looking for
!Street_Name!.strip().split(" ")[:-1] if len(!Street_Name!.strip().split(" "))>1 else !Street_Name!.strip()
-
@faith_dur Thanks but still the same result.geoJshaun– geoJshaun2016年12月01日 23:40:35 +00:00Commented Dec 1, 2016 at 23:40
Explore related questions
See similar questions with these tags.
!Street_Name!.split(" ")[0:-1]