Monday, January 30, 2012

Python - My first plpython function

I needed a function that is able to remove white spaces inside a string in order to rename table and columns to a more standard form. There are probably faster / easier ways to do this, but for now, this will suffice.

postgres=# CREATE OR REPLACE FUNCTION remove_blanks (t text)
RETURNS text
AS $$
import string
result = ""
for char in t:
  if not(char in string.whitespace):
    result = result + char
return result
$$ LANGUAGE plpython2u;
CREATE FUNCTION

postgres=# \df
                                List of functions
 Schema |         Name          | Result data type | Argument data types |  Type  
--------+-----------------------+------------------+---------------------+--------
public | remove_blanks         | text             | t text              | normal


postgres=# select remove_blanks('This string contains spaces');
      remove_blanks       
--------------------------
 Thisstringcontainsspaces
(1 row)

No comments:

Post a Comment