Python Error TypeError: cannot concatenate 'str' and 'float' objects [duplicate]

人盡茶涼 提交于 2019-12-08 14:23:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!