Extract items from string in db
Tobiah
toby at tobiah.org
Wed Mar 15 10:23:19 EDT 2017
On 03/14/2017 03:26 PM, 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.
>
> How can I unpack and access each item?
> Item1: Value1 has,comma
> Item2: has'apostrophe
> Item3: Value3
>
This problem is probably unsolvable for all cases because the data is
apparently allowed to freely contain the characters that provide the
string with its structure. Still, there are clues that enable the
parsing of most normal cases you are likely to encounter. This
hinges on the fact that "','" is unlikely to occur in the actual data:
s = "['Item1: Value1 has,comma','Item2: has'apostrophe','Item3: Value3']"
items = s[2:-2].split("','") # Toss brackets, first and last quotes
for thing in items:
key, val = thing.split(": ")
print "%s: %s" % (key, val)
Output:
-------
Item1: Value1 has,comma
Item2: has'apostrophe
Item3: Value3
More information about the Python-list
mailing list