1

I am trying to fill a field of a shapefile that is delevoped by a number of unions. The content of the field is supposed to inform about the origin of a polygon in the shape.

I am not experienced in python scripts, so my solution is not quite elegant:

def  FillInfo(Info,Info_WB,Info_UESG,Info_GB,Info_Moo,Info_HHS,Info_PT,Info_SN,Info_SA):
return Info_WB + ',' + Info_UESG + ',' + Info_GB + ',' + Info_Moo + ',' + Info_HHS + ',' + Info_PT + ',' + Info_SN + ',' + Info_SA

Info is the field that is supposed to contain the information regarding the origin of the polygon and Info_NN are the fields containing this information.

The problem is, I do not want a row of commas if the fields are empty.

How can I manage to only string together "valid" entries?

5
def  FillInfo(Info,Info_WB,Info_UESG,Info_GB,Info_Moo,Info_HHS,Info_PT,Info_SN,Info_SA):
    returnItems = [Info_WB,Info_UESG,Info_GB,Info_Moo,Info_HHS,Info_PT,Info_SN,Info_SA]
    returnItemsClean = [i for i in returnItems if i]
    return ','.join(returnItemsClean)

The explanation of what the join method does from the Python docs:

string.join(words[, sep]) Concatenate a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character. It is always true that string.join(string.split(s, sep), sep) equals s.

Step by step:

  1. You add your fields to a list
  2. You clean up the list by adding only fields that contain a value
  3. You join the list items with a comma (or whatever other separator you want)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.