Extract items from string in db
Steve D'Aprano
steve+python at pearwood.info
Wed Mar 15 04:02:00 EDT 2017
On Wed, 15 Mar 2017 09:26 am, DFS wrote:
> I have a SQLite database with TEXT columns containing strings of the
> format:
>
> ['Item1: Value1 has,comma','Item2: has'apostrophe','Item3: Value3']
>
> The brackets are part of the string.
So in Python format, you have something like this:
s = "['Item1: Value1 has,comma','Item2: has'apostrophe','Item3: Value3']"
assert type(s) is str
assert s[0] == "["
assert s[-1] == "]"
Correct?
I can't help you in getting s out of the SQLite database. Below, you tell us
that you're extracting the string, but it isn't actually a string, it is a
tuple. You need to fix that.
> How can I unpack and access each item?
> Item1: Value1 has,comma
> Item2: has'apostrophe
> Item3: Value3
Is the string format documented anywhere?
> I tried this:
> db.execute("SELECT COLUMN FROM TABLE WHERE ID = ?;",(123,))
> vals = [db.fetchone()]
> for val in list(vals):
> print val
There's no point wrapping the output of db.fetchone() in a list. And no
point converting vals to a list.
db.execute("SELECT COLUMN FROM TABLE WHERE ID = ?;", (123,))
vals = db.fetchone()
for val in vals:
print type(val), val
What does it output now?
> but it just prints the string as is.
>
> split(",") returns "tuple object has no attribute split"
If it is a tuple object, it isn't a string. It isn't both at once.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list