I have a table and in that table I have field Fld_1 and I would like to move the text after the comma to the front of the attribute and remove the comma. Not all attributes will have a comma.
I am able to split the filed attrubutes but am not sure how to work with the comma ','.
with arcpy.da.UpdateCursor(Table, ['Fld_1']) as cursor:
for row in cursor:
row[0] = " ".join(row[0].split()[:3])
cursor.updateRow(row)
del cursor
Example
Island Village, The --> The Island Village
How fancy do you want to get??
def r(a, pad=" "):
if "," in a:
b = a.split(",")
c = b[1].strip() + pad + b[0]
else:
return a
return c
r("first, last")
'last first'
I would use rsplit() to ensure you only split once on the last separator. You can use .reverse() to put the last value first, then join it all back together.
with arcpy.da.UpdateCursor(Table, ['Fld_1']) as cursor:
for row in cursor:
value_split = row[0].rsplit(", ", 1)
value_split.reverse()
row[0] = " ".join(value_split)
cursor.updateRow(row)
Also note: you don't need to del the cursor when using with
Check for the presence of a comma. Treat row[0] as a list, pop() off the last member of that list and glue the whole mess back together, replacing the comma....
with arcpy.da.UpdateCursor(Table, ['Fld_1']) as cursor:
for row in cursor:
if ',' not in row[0]:
pass
elif ',' in row[0]:
rowList = row[0].split(' ')
first = rowList.pop()
last = ' '.join(rowList)
newRow = f'{first} {last}'.replace(',','')
row[0] = newRow
cursor.updateRow(row)
Can't believe I forgot about pop()!
That's what's so fun about a post like this! Several different approaches that all work. I've never ever used rsplit(). Joshua's nested map() is pretty cool too! Just hope the OP isn't overwhelmed!
Haha, yeah, we all jumped on this like a pack of hungry wolves pythons.
The Python questions must be light lately, everyone has pent up energy to write some code snippets.
Just for the code golf fun of it:
>>> s = "Island Village, The"
>>> " ".join(reversed(list(map(str.strip, s.split(',')))))
'The Island Village'
>>>
>>> s = "Peninsula Town"
>>> " ".join(reversed(list(map(str.strip, s.split(',')))))
'Peninsula Town'
>>>
I love the contrast in our styles!