Remove and replace first space character from a field in an attribute table

930
2
Jump to solution
04-19-2019 10:13 AM
StewartGalloway
New Contributor III

How can I remove and replace the first space characters from a field (a person's name)  in an attribute table?  Adn replace it with a comma.

FROM: Doe M Jane TO: Doe, M Jane.

I have been switching the names to Jane Doe by the following Python:

" ".join( !PRIMARY_OWNER! .split(", ").__reversed__())

This works perfectly but quite a few names do not include a comma.

Thanks.

0 Kudos
1 Solution

Accepted Solutions
RandyBurton
MVP Regular Contributor

Some things to try (assuming there is no space in the last name - that is not  a name like Van Gogh):

>>> name = 'Doe M Jane'
>>> ', '.join(name.split(" ", 1))
'Doe, M Jane'

>>> " ".join(name.split(" ", 1).__reversed__()).replace(',','')
'M Jane Doe'

>>> name = 'Doe, M Jane'
>>> if ',' not in name:
	', '.join(name.split(" ", 1))


>>> name
'Doe, M Jane'

>>> name = 'Doe M Jane'
>>> if ',' not in name:
	', '.join(name.split(" ", 1))

	
'Doe, M Jane'

View solution in original post

2 Replies
RandyBurton
MVP Regular Contributor

Some things to try (assuming there is no space in the last name - that is not  a name like Van Gogh):

>>> name = 'Doe M Jane'
>>> ', '.join(name.split(" ", 1))
'Doe, M Jane'

>>> " ".join(name.split(" ", 1).__reversed__()).replace(',','')
'M Jane Doe'

>>> name = 'Doe, M Jane'
>>> if ',' not in name:
	', '.join(name.split(" ", 1))


>>> name
'Doe, M Jane'

>>> name = 'Doe M Jane'
>>> if ',' not in name:
	', '.join(name.split(" ", 1))

	
'Doe, M Jane'
JimCousins
MVP Regular Contributor

Randy has perfectly workable code, but a simple snippet could be:

>>> import arcpy
>>> str = "Doe M Jane"
>>> string.replace(" ", ", ",1)
'Doe, M Jane'

 ".replace" looks for  the string in the first argument, and replaces it with the string in the second argument, and the last argument is the number of substitutions to make.

So, it is looking for a space and replacing it with a comma and a space, and doing it only for the first instance it finds.

Regards, 

Jim