问题
I am new with Python programming. I keep getting the below error on the 'str'. When I added the + str, it didnt work.
wkt = "POINT("+ geoPoint["lat"] +" " + geoPoint["lon"] + ")"
TypeError: cannot concatenate 'str' and 'float' objects
Any advice on how I can fix this error?
回答1:
The simplest solution would look like this:
wkt = "POINT("+ str(geoPoint["lat"]) +" " + str(geoPoint["lon"]) + ")"
The following would be more in line with accepted Python stylistic standards:
wkt = "POINT(%f %f)" % (geoPoint["lat"], geoPoint["lon"])
This uses the simplest form of string formatting
You could do something nicer still:
wkt = "POINT({lat} {lon}".format(**geoPoint)
See the linked page for more ideas on this.
回答2:
Not able to concatenate 'str' and 'float' with '+'
Best way to concatenate string and float in python.Use format function:
wkt = "POINT({} {})".format(geoPoint["lat"], geoPoint["lon"])
Also use:
>>>wkt = "POINT(%s %s)" % (geoPoint["lat"], geoPoint["lon"])
>>>'s'+2 # use like this.It will raise type error exception
TypeError: cannot concatenate 'str' and 'float' objects
>>>'%s%s' % ('s', 2)
's2'
>>>'POINT({}{})'.format(geoPoint["lat"], geoPoint["lon"])
# It will print your value
来源:https://stackoverflow.com/questions/43971280/python-error-typeerror-cannot-concatenate-str-and-float-objects