开发者

how to convert value of column defined as character into integer in python

开发者 https://www.devze.com 2023-02-13 19:58 出处:网络
I had a postgresql query where I need to take colu开发者_如何学运维mn defined as character from table and then pass this value to the function where it only accepts integer.So in this case, how can i

I had a postgresql query where I need to take colu开发者_如何学运维mn defined as character from table and then pass this value to the function where it only accepts integer.So in this case, how can i solve the problem??Can anyone help??


Don't forget to use try/except statements in conversion to avoid surprises like this:

Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a='a'
>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'

Solution:

try:
    int(myvar)
except ValueError:
    ...Handle the exception...


ord(val) will give you the integer value of a character. int(val) will cast a value into an integer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号