Michael Tobey
Michael Tobey

Reputation: 21

ArcGIS:Python - Adding Commas to a String

In ArcGIS I have intersected a large number of zonal polygons with another set and recorded the original zone IDs and the data they are connected with. However the strings that are created are one long list of numbers ranging from 11 to 77 (each ID is 11 characters long). I am looking to add a "," between each one making, it easier to read and export later as a .csv file. To do this I wrote this code:

def StringSplit(StrO,X):
  StrN = StrO #Recording original string 
  StrLen = len(StrN) 
  BStr = StrLen/X #How many segments are inside of one string
  StrC = BStr - 1 #How many times it should loop
  if StrC > 0:  
    while StrC > 1:
      StrN = StrN[ :((X * StrC) + 1)] + "," + StrN[(X * StrC): ]
      StrC = StrC - 1
    while StrC == 1:
      StrN = StrN[:X+1] + "," + StrN[(X*StrC):]
      StrC = 0 
    while StrC == 0:
      return StrN
  else:
    return StrN

The main issue is how it has to step through multiple rows (76) with various lengths (11 -> 77). I got the last parts to work, just not the internal loop as it returns an error or incorrect outputs for strings longer than 22 characters.

Thus right now:

1. 01234567890 returns 01234567890

2. 0123456789001234567890 returns 01234567890,01234567890

3. 012345678900123456789001234567890 returns either: Error or ,, or even ,,01234567890

I know it is probably something pretty simple I am missing, but I can't seem remember what it is...

Upvotes: 1

Views: 226

Answers (2)

Nihal
Nihal

Reputation: 5334

It can be easily done by regex. those ........... are 11 dots for give split for every 11th char.

you can use pandas to create csv from the array output

Code:

import re

x = re.findall('...........', '01234567890012345678900123456789001234567890')

print(x)
myString = ",".join(x)

print(myString)

output:

['01234567890', '01234567890', '01234567890', '01234567890']
01234567890,01234567890,01234567890,01234567890

for the sake of simplicity you can do this

code:

x = ",".join(re.findall('...........', '01234567890012345678900123456789001234567890'))


print(x)

Upvotes: 1

Gelineau
Gelineau

Reputation: 2090

Don't make the loops by yourself, use python libraries or builtins, it will be easier. For example :

def StringSplit(StrO,X):
    substring_starts = range(0, len(StrO), X)
    substrings = (StrO[start:start + X] for start in substring_starts)
    return ','.join(substrings)

string = '1234567890ABCDE'
print(StringSplit(string, 5))

# '12345,67890,ABCDE'

Upvotes: 1

Related Questions