[Tutor] Converting from unicode to nonstring

Dave Angel davea at ieee.org
Fri Oct 15 14:51:15 CEST 2010

On 2:59 PM, David Hutto wrote:
> Ok, Let me restate and hopefully further clarify.
> 1. I have a field for a wxpython app using matplotlib to display
> 2. I have a sqlite3 db which I'm retrieving information from
> 3. The sqlitle data is returned as unicode: u'field'
> 4. The portion of the matplotlib code is filled in, in a for x in y:
> 5. in plot(self.plot), self.plot is the variable I'm using from the unicoded db
> field comes in from sqlite as u'[1,2,3,4]', which places a string in quotes in
> that variables place:
> plot(u'[1,2,3,4]')
> <snip>
Your point #5 shows that you still have the wrong handle on what a 
literal string is.

When you write in code
mystring = u"abc"

The u and the quote symbols are *not* in "the variables place".  The 
"variables place" contains a count, three characters, and some meta 
information.  The time you need the quotes are when you want to specify 
those three characters in your source code.  The time you get the quotes 
back is when you use repr(mystring) to display it.  If you use    print 
mystring   you don't see any quotes or 'u', nor do you when you call the 
function str(mystring).

So I'll try to explain some terminology.  When you run the source code

mystring = u"abc"

the interpreter (with help from the compiler) builds an object of type 
string, with contents of those three letters.  That object is bound to 
the name mystring.  Nowhere is a u or a quote to be found.

Now, the question is how to turn that string object into a list, since 
apparently plot() is looking for a list.  Judging from the error 
message, it may also be happy to take a float.  So it'd be good to find 
out just what types of objects it's willing to accept.

One of the first respondents on the thread showed how to convert this 
particular string into a list, but he made the implicit assumption that 
the values in the list were single-digit integer values.  I haven't seen 
you ever define what the possible values are.  But guessing that they 
are supposed to be a list containing a nonzero number of floats, 
separated by commas, you could do something like (untested):

     result = [float(strvalue) for strvalue in mystring.split(",")]

or, more straightforward:

       strvalues = mystring.split(",")      # get a list of strings, 
split by the comma
       result = []
       for  strvalue in strvalues:
              result.append(float(strvalue))         #convert to float

Notice, nothing about quotes, or unicode anywhere in the logic.


More information about the Tutor mailing list