Store fieldnames in a string variable

316
3
Jump to solution
03-20-2024 05:54 AM
Ed_
by MVP Regular Contributor
MVP Regular Contributor

Usually one can get the list of field/column names using the following code. Now, I would like to store the field names as strings in a variable. How can I do this?

Desired output:

 

 

var = ("Field 1", "Field2", "Field.3")

 

 

Another try (does not work either):

 

for field in fields:
    var = str(field.name)

Current code:

 

 

fields = arcpy.ListFields('df')
# Show column names
for field in fields:
    print(field.name)

 

 

 

Question | Analyze | Visualize
0 Kudos
2 Solutions

Accepted Solutions
RichardHowe
Occasional Contributor III

I've taken what you asked for quite literally (i.e. replaced single speech-marks with doubles and square brackets with curly) hence the multiple replace operations on the final variable but I think it should achieve what you're after

 

 

fields = arcpy.ListFields('df')
fieldlist = []
for field in fields:
  fieldlist.append(field.name)

var = str(fieldlist).replace("'", '"').replace("[", "(").replace("]", ")")
print var

 

 

View solution in original post

JoshuaBixby
MVP Esteemed Contributor

The major issue you are having is that arcpy.ListFields returns just that, fields or field objects, and not field names. 

var = [field.name for field in arcpy.ListFields('df')]

View solution in original post

3 Replies
RichardHowe
Occasional Contributor III

I've taken what you asked for quite literally (i.e. replaced single speech-marks with doubles and square brackets with curly) hence the multiple replace operations on the final variable but I think it should achieve what you're after

 

 

fields = arcpy.ListFields('df')
fieldlist = []
for field in fields:
  fieldlist.append(field.name)

var = str(fieldlist).replace("'", '"').replace("[", "(").replace("]", ")")
print var

 

 

JoshuaBixby
MVP Esteemed Contributor

The major issue you are having is that arcpy.ListFields returns just that, fields or field objects, and not field names. 

var = [field.name for field in arcpy.ListFields('df')]
Ed_
by MVP Regular Contributor
MVP Regular Contributor

Hi Joshua, I might ping you, if you have sometime, since now I am trying to combine the code in your reply with the code you helped with earlier in the split comma separated values post. Thank you!

Question | Analyze | Visualize
0 Kudos