简体   繁体   中英

python convert “unicode” as list

I have a doubt about treat a return type in python.

I have a database function that returns this as value:

(1,13616,,"My string, that can have comma",170.90)

I put this into a variable and did test the type:

print(type(var))

I got the result:

<type 'unicode'>

I want to convert this to a list and get the values separeteds by comma.

Ex.:

var[0] = 1
var[1] = 13616
var[2] = None
var[3] = "My string, that can have comma"
var[4] = 170.90

Is it possible?

Using standard library csv readers:

>>> import csv
>>> s = u'(1,13616,,"My string, that can have comma",170.90)'
>>> [var] = csv.reader([s[1:-1]])
>>> var[3]
'My string, that can have comma'

Some caveats:

  • var[2] will be an empty string, not None , but you can post-process that.
  • numbers will be strings and also need post-processing, since csv does not tell the difference between 0 and '0' .

You can try to do the following:

b = []
for i in a:
    if i != None:
        b.append(i)
    if i == None:
        b.append(None)

print (type(b))

The issue is not with the comma.

this works fine:

a = (1,13616,"My string, that can have comma",170.90)

and this also works:

a = (1,13616,None,"My string, that can have comma",170.90)

but when you leave two commas ",," it doesn't work.

Unicode strings are (basically) just strings in Python2 (in Python3, remove the word "basically" in that last sentence). They're written as literals by prefixing a u before the string (compare raw-strings r"something" , or Py3.4+ formatter strings f"{some_var}thing" )

Just strip off your parens and split by comma. You'll have to do some post-parsing if you want 170.90 instead of u'170.90' or None instead of u'' , but I'll leave that for you to decide.

>>> var.strip(u'()').split(u',')
[u'1', u'13616', u'', u'"My string', u' that can have comma"', u'170.90']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM