Showing posts with label cleaning row database data by python. Show all posts
Showing posts with label cleaning row database data by python. Show all posts

Tuesday, December 29, 2015

How to eliminate u' while retrieving values from database

I am currently working with Flask web development platform which supports python programming and jinja2. I used sqite3 for my database. The development part is going well but whenever I tried to retrieve a value from database I get something like - (u'The value original one', ). It is very annoying . You can do nothing much about it but to modify your program to handle it.
Regular expression is very handy to resolve this kind of problem. You can also use the split function of string. Lets do it by split first -

import sqlite3
db=sqlite3.connect('irms')
cur=db.cursor() 
cur.execute("select  id from some_table")
allidraw=cur.fetchall()
print allidraw##It will show the data as a  list with u' in each element
allid=[]
for each_data in data:                   
                    print allidraw
                    for row in allidraw:
                        row=str(row)
                        print "????????",row
                        try:
                            row=row.split("'")
                            row=row[1]
                            allid.append(str(row))
                        except:
                            allid.append(str(row))
                    print "********",allid


Now the allid will hold the values without any u'. You can see we converted the each element to string and then split it by the "  '  "and then get the first element as the needed value.

You can do the same thing with regular expression. To do so follow the below steps - 

import re
data="[(u'WBPDCL 2',)]"  #you will get this type of output from sqlite as a result of db operations
x=re.findall('[(A-Z)+]+\s+[(0-9)+]',data)
print x

The regular expression will extract the character and numerical element with spaces but skip the u'. You can try it. A very easy way to eliminate those u's.




Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...