RE: string to list
This will do you job: a = 'AAA,,,,EEE,FFF,GGG' b = [] for x in a.split(','): ... if (x.find(\) -1): ... x = x.strip(\) ... b.append(x) If you want reduce the lines of code u can go for this option: b = [x.strip(\) for x in a.split(',')] So Just Cheerz, -Shambhu -Original Message- From: bruce g [mailto:bruceg113...@gmail.com] Sent: 14/06/2012 8:00 AM To: python-list@python.org Subject: string to list What is the best way to parse a CSV string to a list? For example, how do I parse: 'AAA,,,,EEE,FFF,GGG' to get: ['AAA','BBB,CCC,','EEE','FFF','GGG'] Thanks, Bruce -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
bruce g wrote: What is the best way to parse a CSV string to a list? For example, how do I parse: 'AAA,,,,EEE,FFF,GGG' to get: ['AAA','BBB,CCC,','EEE','FFF','GGG’] import csv next(csv.reader(['AAA,,,,EEE,FFF,GGG'])) ['AAA', ',,', 'EEE', 'FFF', 'GGG'] For multiple records: list(csv.reader(text.splitlines(True))) -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
Hi, You can use literal_eval from ast package. from ast import literal_eval list(literal_eval('aa','bb','cc') this will return ['aa', 'bb', 'cc'] Thanks, Anoop Thomas Mathew atm ___ Life is short, Live it hard. On 14 June 2012 12:28, Shambhu Rajak shambhu.ra...@kpitcummins.com wrote: This will do you job: a = 'AAA,,,,EEE,FFF,GGG' b = [] for x in a.split(','): ... if (x.find(\) -1): ... x = x.strip(\) ... b.append(x) If you want reduce the lines of code u can go for this option: b = [x.strip(\) for x in a.split(',')] So Just Cheerz, -Shambhu -Original Message- From: bruce g [mailto:bruceg113...@gmail.com] Sent: 14/06/2012 8:00 AM To: python-list@python.org Subject: string to list What is the best way to parse a CSV string to a list? For example, how do I parse: 'AAA,,,,EEE,FFF,GGG' to get: ['AAA','BBB,CCC,','EEE','FFF','GGG'] Thanks, Bruce -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
@Annop Nice one, but you seem to have missed a parenthesis. list(literal_eval('aa','bb','cc') should have been list(literal_eval('aa','bb','cc')) On Thu, Jun 14, 2012 at 12:58 PM, Anoop Thomas Mathew atm...@gmail.comwrote: list(literal_eval('aa','bb','cc') -- *'I am what I am because of who we all are'* h3manth.com http://www.h3manth.com *-- Hemanth HM * -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
list(literal_eval('aa,bb 'b',cc')) ['aa', 'bb ', 'cc'] Strange? On Thu, Jun 14, 2012 at 1:09 PM, Hemanth H.M hemanth...@gmail.com wrote: @Annop Nice one, but you seem to have missed a parenthesis. list(literal_eval('aa','bb','cc') should have been list(literal_eval('aa','bb','cc')) On Thu, Jun 14, 2012 at 12:58 PM, Anoop Thomas Mathew atm...@gmail.comwrote: list(literal_eval('aa','bb','cc') -- *'I am what I am because of who we all are'* h3manth.com http://www.h3manth.com *-- Hemanth HM * -- *'I am what I am because of who we all are'* h3manth.com http://www.h3manth.com *-- Hemanth HM * -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
@group: Sorry for the mistake. @Hemanth: Thank You for pointing out. I just realized that, we should not copy paste from the console. :) atm ___ Life is short, Live it hard. On 14 June 2012 13:09, Hemanth H.M hemanth...@gmail.com wrote: @Annop Nice one, but you seem to have missed a parenthesis. list(literal_eval('aa','bb','cc') should have been list(literal_eval('aa','bb','cc')) -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
On Thu, Jun 14, 2012 at 12:40 AM, Hemanth H.M hemanth...@gmail.com wrote: list(literal_eval('aa,bb 'b',cc')) ['aa', 'bb ', 'cc'] Strange? Not really. You didn't properly escape the embedded quotation marks in the string itself! So before anything ever even gets passed to literal_eval(), that part is parsed as two adjacent literals: 'aa,bb ' and b',cc' In Python 3.x, the b prefix indicates a `bytes` literal rather than a `str` literal. Implicit adjacent string literal concatenation then occurs. Thus: print 'aa,bb ' b',cc' aa,bb ,cc Compare: print '''aa,bb 'b',cc''' aa,bb 'b',cc But really, literal_eval() should not be used for CSV; it won't handle unquoted fields at all, among other issues. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
n Wed, Jun 13, 2012 at 7:29 PM, bruce g bruceg113...@gmail.com wrote: What is the best way to parse a CSV string to a list? Use the `csv` module: http://docs.python.org/library/csv.html http://www.doughellmann.com/PyMOTW/csv/ The `StringIO` module can be used to wrap your string as a file-like object for consumption by the `csv` module: http://docs.python.org/library/stringio.html Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
string.split(',') will give you an array. Example: 'AAA,,,,EEE,FFF,GGG '.split(',') ['AAA', '', '', '', 'EEE', 'FFF', 'GGG'] On Wed, Jun 13, 2012 at 10:53 PM, Chris Rebert c...@rebertia.com wrote: n Wed, Jun 13, 2012 at 7:29 PM, bruce g bruceg113...@gmail.com wrote: What is the best way to parse a CSV string to a list? Use the `csv` module: http://docs.python.org/library/csv.html http://www.doughellmann.com/PyMOTW/csv/ The `StringIO` module can be used to wrap your string as a file-like object for consumption by the `csv` module: http://docs.python.org/library/stringio.html Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list
On Wed, Jun 13, 2012 at 10:06 PM, Jose H. Martinez josehmartin...@gmail.com wrote: string.split(',') will give you an array. Example: 'AAA,,,,EEE,FFF,GGG '.split(',') ['AAA', '', '', '', 'EEE', 'FFF', 'GGG'] But it incorrectly splits the quoted part. A proper CSV parser (like the csv module) should leave that part as a single string, even though it contains commas. -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
Wes James wrote: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] The [] is simple since I can just check if value == [] then return [] But with ['a','b'] I have tried and get: a=['a','b'] b=a[1:-1].split(',') returns [ 'a' , 'b' ] when I want it to return ['a','b']. How can I do this? thx, -wes I am surprised nobody gave you the simple answer yet that may even work for your situation: b=a[2:-2].split(',') -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
Wes James wrote: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] The [] is simple since I can just check if value == [] then return [] But with ['a','b'] I have tried and get: a=['a','b'] b=a[1:-1].split(',') returns [ 'a' , 'b' ] when I want it to return ['a','b']. Just to add to the list of solutions I've seen, letting the built-in csv module do the heavy lifting: s = ['a','b'] import csv no_brackets = s[1:-1] # s.strip(' \t[]') c = csv.reader([no_brackets], quotechar=') c.next() ['a', 'b'] This also gives you a bit of control regarding how escaping is done, and other knobs dials to twiddle if you need. Additionally, if you have more than one string to process coming from an iterable source (such as a file), you can just pass that iterator to csv.reader() instead of concocting a one-element list. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase python.l...@tim.thechases.com wrote: Wes James wrote: snip Just to add to the list of solutions I've seen, letting the built-in csv module do the heavy lifting: s = ['a','b'] import csv no_brackets = s[1:-1] # s.strip(' \t[]') c = csv.reader([no_brackets], quotechar=') c.next() ['a', 'b'] This also gives you a bit of control regarding how escaping is done, and other knobs dials to twiddle if you need. Additionally, if you have more than one string to process coming from an iterable source (such as a file), you can just pass that iterator to csv.reader() instead of concocting a one-element list. Thx, I think this will work for what I want. -wes -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Thu, Feb 18, 2010 at 12:32 PM, Wes James compte...@gmail.com wrote: On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase python.l...@tim.thechases.com wrote: Wes James wrote: snip Just to add to the list of solutions I've seen, letting the built-in csv module do the heavy lifting: s = ['a','b'] import csv no_brackets = s[1:-1] # s.strip(' \t[]') c = csv.reader([no_brackets], quotechar=') c.next() ['a', 'b'] Hmm. When I put csv.reader in a class: import csv class IS_LIST(): def __init__(self, format='', error_message='must be a list!'): self.format = format self.error_message = error_message def __call__(self, value): try: if value=='[]' or value=='': value=[] else: no_brackets = value[1:-1] # s.strip(' \t[]') c = csv.reader([no_brackets], quotechar=') value=c.next() return (value, None) except: return (value, self.error_message) def formatter(self, value): return value I get an error (when I take the try out): AttributeError: 'function' object has no attribute 'reader' Why? -wes -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
import csv class IS_LIST(): def __init__(self, format='', error_message='must be a list!'): self.format = format self.error_message = error_message def __call__(self, value): try: if value=='[]' or value=='': value=[] else: no_brackets = value[1:-1] # s.strip(' \t[]') c = csv.reader([no_brackets], quotechar=') value=c.next() return (value, None) except: return (value, self.error_message) def formatter(self, value): return value I get an error (when I take the try out): AttributeError: 'function' object has no attribute 'reader' A couple ideas occur to me: 1) you haven't copy/pasted the exact (or entirety of the) code, and something you're doing is shadowing the csv module 2) are you using Python 2.x or 3.x? I don't know if the csv module has changed in 3.x but it should work in 2.x The first thing to check would be to pull up a raw python prompt and see if your csv module has the expected reader: import csv csv.reader built-in function reader If not, something likely changed in 3.x and you'd have to inspect the docs to see what happened to the reader. If you get the above evidence of an existing reader, then you're likely shadowing it. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Thu, Feb 18, 2010 at 2:56 PM, Wes James compte...@gmail.com wrote: I get an error (when I take the try out): AttributeError: 'function' object has no attribute 'reader' You have a function called csv that's defined after the import csv statement is executed. That function has no attribute 'reader, so you get the error. By the way, don't use a bare except- it's bad form because it hides any other problems you have. -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
In article mailman.2736.1266522979.28905.python-l...@python.org, Wes James compte...@gmail.com wrote: try: if value=3D=3D'[]' or value=3D=3D'': value=3D[] else: no_brackets =3D value[1:-1] # s.strip(' \t[]') c =3D csv.reader([no_brackets], quotechar=3D') value=3Dc.next() return (value, None) except: return (value, self.error_message) Two important points: * Don't use bare except: clauses * Put less code in the try: clause to make it easier to track down problems -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ At Resolver we've found it useful to short-circuit any doubt and just refer to comments in code as 'lies'. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Thu, 18 Feb 2010 14:52:29 -, nn prueba...@latinmail.com wrote: Wes James wrote: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] The [] is simple since I can just check if value == [] then return [] But with ['a','b'] I have tried and get: a=['a','b'] b=a[1:-1].split(',') returns [ 'a' , 'b' ] when I want it to return ['a','b']. How can I do this? thx, -wes I am surprised nobody gave you the simple answer yet that may even work for your situation: b=a[2:-2].split(',') Because it's really *very* not robust. Harmless whitespace defeats it for starters, and that's one of the most likely things to vary between example data and reality. If you trust your data to be well-formed enough for this to work, you might as well use eval() instead. If you don't, parsing is the only sensible answer. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
2010/2/18 Wes James compte...@gmail.com: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] The [] is simple since I can just check if value == [] then return [] But with ['a','b'] I have tried and get: a=['a','b'] b=a[1:-1].split(',') returns [ 'a' , 'b' ] when I want it to return ['a','b']. How can I do this? thx, -wes -- http://mail.python.org/mailman/listinfo/python-list The potentially problematic exec or eval options left aside, if you really need to do this, you might consider pyparsing; check the example http://pyparsing.wikispaces.com/file/view/parsePythonValue.py If you know, the input string will always have this exact format (single quoted comma separated one-character strings between square brackets), you might use regular expressions to some extent, e.g. print re.findall(r(?=')\w(?='), ['a','b','c','b','A']) ['a', 'b', 'c', 'b', 'A'] hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Wed, 17 Feb 2010 23:48:38 -, Wes James compte...@gmail.com wrote: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] If your string is trusted (i.e. goes nowhere near a user), just eval() it. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
On Thu, 18 Feb 2010 00:13:05 +, Rhodri James wrote: On Wed, 17 Feb 2010 23:48:38 -, Wes James compte...@gmail.com wrote: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] If your string is trusted (i.e. goes nowhere near a user), just eval() it. Or use something like YAML or JSON to parse it. Fredrik Lundh has a simple_eval function which should be safe to use: http://effbot.org/zone/simple-iterator-parser.htm But it's fairly simple to parse a simple list like this. Here's a quick and dirty version: def string_to_list(s): s = s.strip() if not s.startswith('[') and s.endswith(']'): raise ValueError s = s[1:-1].strip() items = [item.strip() for item in s.split(',')] for i, item in enumerate(items): items[i] = dequote(item) return items def dequote(s): for delimiter in ('', ''', '', '): if s.startswith(delimiter) and s.endswith(delimiter): n = len(delimiter) return s[n:-n] raise ValueError s = ['a','b'] print s ['a','b'] string_to_list(s) ['a', 'b'] x = string_to_list(s) type(x) type 'list' x ['a', 'b'] -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
Wes James comptekki at gmail.com writes: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] The [] is simple since I can just check if value == [] then return [] But with ['a','b'] I have tried and get: a=['a','b'] b=a[1:-1].split(',') returns [ 'a' , 'b' ] when I want it to return ['a','b']. How can I do this? eval will work, but has a safety issue. It also has the issue of evaluating any and everything that a user might pass in. If you are using python 2.6 check out ast.literal_eval. It uses python's built in ast parser to generate an AST and then traverses it to generate a python object. Unlike eval though, it will raise an exception if anything other than a literal is represented in the string. I have used the same function in python 2.5 (copied from 2.6) and it works just fine. Here is a version modified from the code in python 2.6 that should only parse lists of strings: from _ast import List, Str, PyCF_ONLY_AST def parse(expr, filename='unknown', mode='exec'): Parse an expression into an AST node. Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST). return compile(expr, filename, mode, PyCF_ONLY_AST) def list_eval(text): Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. node = parse(text, mode='eval').body if not isinstance(node, List): raise ValueError('malformed string') def _convert(node): if isinstance(node, Str): return node.s raise ValueError('malformed string') return list(map(_convert, node.elts)) Matt McCredie -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list when the contents is a list
Wes James compte...@gmail.com writes: I have been trying to create a list form a string. The string will be a list (this is the contents will look like a list). i.e. [] or ['a','b'] Pulling back to ask about the larger problem: Are you trying to create Python data structures from a serialised representation? There are several well-implemented solutions, including the standard library modules ‘pickle’ and ‘json’. Do you have control over the choice of serialisation format? -- \“I went to court for a parking ticket; I pleaded insanity. I | `\ said ‘Your Honour, who in their right mind parks in the passing | _o__) lane?’” —Steven Wright | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: String to List Question
On Jul 2, 2009, at 6:05 PM, Hanna Michelsen wrote: Hi, I am brand new to python and I love it, but I've been having some trouble with a file parser that I've been working on. It contains lines that start with a name and then continue with names, nicknames and phone numbers of people associated with that name. I need to create a list of the names of people associated with each singular person (the first name in each line). Each name/phone number is separated by a tab but if someone doesn't have a nickname there are two tabs between their name and number. I've been trying to figure out how to test for two tabs, skip over these people and move onto the next name but I just can't figure out how that will work in python. Any help would be greatly appreciated! Hi Hanna, Are you familiar with a string's split() function? It sounds like just what you need. http://docs.python.org/library/stdtypes.html#str.split HTH Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: String to List Question
On Thu, 02 Jul 2009 23:05:46 +0100, Hanna Michelsen hannaro...@gmail.com wrote: Hi, I am brand new to python and I love it, but I've been having some trouble with a file parser that I've been working on. It contains lines that start with a name and then continue with names, nicknames and phone numbers of people associated with that name. I need to create a list of the names of people associated with each singular person (the first name in each line). Each name/phone number is separated by a tab but if someone doesn't have a nickname there are two tabs between their name and number. I've been trying to figure out how to test for two tabs, skip over these people and move onto the next name but I just can't figure out how that will work in python. You might find the csv module in the standard library does a lot of the hard work for you: http://docs.python.org/library/csv.html You can define yourself a reader that splits the input on tabs, and then see how long the rows it returns are. Something like this (untested): import csv for row in csv.reader(open(phone_numbers.txt, rb), delimiter='\t'): if len(row) 1: # Do your stuff -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list conversion
John Forse wrote: I need to convert an input string say '' to a list of the form ['' ,]. If I use list(stringname), I get ['x','x','x','x'] ; list.join() is an error; and str.join() won't use lists. I do need the comma after the string. Is there a simple solution? Suppose your input string is s. Just say s = [s] Bingo, s is now a list containing the input string as its only element. But I suspect that's not what you mean ... because you say I do need the comma after the string. Do you mean that you want to produce a string containing ['', ]? You might try s = ['%s', ] % s But that's potentially going to give you problems if s contains either an apostrophe or a quote mark. It depends how you plan to use it. So what is it you want, exactly, and (if it's not asking too much) why? regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list conversion
John Forse wrote: I need to convert an input string say '' to a list of the form ['' ,]. If I use list(stringname), I get ['x','x','x','x'] ; list.join() is an error; and str.join() won't use lists. I do need the comma after the string. Is there a simple solution? Have you tried [stringname], eg ['' ,]? :-) Why do you need the comma? Python permits it but it isn't necessary: ['' ,] [''] -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list conversion
John, Try the following code .. hope this helps and solves your problem . I have run in the interactive mode s='' a=[s,'12'] print a ['', '12'] regards Srinivas -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
On Mar 17, 1:15 am, Girish [EMAIL PROTECTED] wrote: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'') for s in a.strip('[]').split(', ')] -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
Girish [EMAIL PROTECTED] writes: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... Be careful about using eval, if the string came from a potentially hostile source. Maybe what you really want is JSON, which has python-like syntax but a bunch of safe parsers. -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
On Mar 17, 3:22 am, Paul Rubin http://[EMAIL PROTECTED] wrote: Girish [EMAIL PROTECTED] writes: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... Be careful about using eval, if the string came from a potentially hostile source. Maybe what you really want is JSON, which has python-like syntax but a bunch of safe parsers. Or take a look at a restricted safe eval variant (e.g. http://groups.google.com/group/comp.lang.python/browse_frm/thread/262d479569b1712e) George -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
On Mar 17, 6:56 am, Dan Bishop [EMAIL PROTECTED] wrote: On Mar 17, 1:15 am, Girish [EMAIL PROTECTED] wrote: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'') for s in a.strip('[]').split(', ')] This will fall over if xyz or abc include any of the characters your stripping/splitting on (e.g if xyz is actually To be or not to be, that is the question). Unless you can guarantee they won't, you'll need to write (or rather use) a parser that understands the syntax. Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
On Mar 17, 9:27 am, Iain King [EMAIL PROTECTED] wrote: On Mar 17, 6:56 am, Dan Bishop [EMAIL PROTECTED] wrote: On Mar 17, 1:15 am, Girish [EMAIL PROTECTED] wrote: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'') for s in a.strip('[]').split(', ')] This will fall over if xyz or abc include any of the characters your stripping/splitting on (e.g if xyz is actually To be or not to be, that is the question). Unless you can guarantee they won't, you'll need to write (or rather use) a parser that understands the syntax. Iain Thinking about this some more; could the string module not use a simple tokenizer method? I know that relentlessly adding features to built-ins is a bad idea, so I'm not sure if this falls within batteries-included, or is actually just adding bulk. On the one hand, it's not difficult to write a simple state-based token parser yourself, but on the other it is also quite easy to include a pile of bugs when you do. By simple I mean something like: def tokenize(string, delim, closing_delim=None, escape_char=None) which would return a list (or a generator) of all the parts of the string enclosed by delim (or which begin with delim and end with closing_delim if closing_delim is set), ignoring any delimiters which have been escaped by escape_char. Throw an exception if the string is malformed? (odd number of delimiters, or opening/closing delims don't match) In the OP's case, he could get what he want's with a simple: l = a.tokenize(') The point of this ramble not being that this is a how to solve the OP's question, but wondering if it would be a good inclusion to the language in general. Or there's actually a module which already does it that I couldn't find and I'm an idiot... Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
It's too bad your inner data items are delimited with an apostrophe (') instead a double-quote (). If they were double-quote, you could do something as simple as: Given: a = '[xyz, abc]' import simplejson answer = simplejson.loads(a) There may be an incantation to simplejson that allows you to use a different delimiter. You might be able to provide your own decoder, using the cls= argument (but I don't think that lets you change the delimiter string). Failing that, and depending on your regex/Python prowess, you might be able to change the decoder.py file within simplejson to do what you want. As others have observed, a lot depends on the input data. If it really is as simple as your example, then the following may do the trick: a = ['xyz', 'abc'] answer = map(lambda each: each.strip()[1:-1], a[1:-1].split(',')) This at least has no eval, and so you need not fear applying it to unknown data (it will just break). The answer that works best for you may perhaps be somewhere in the middle. Girish [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Thanks for the help... eval(a) will do the job, but you have to be very careful about using that function. An alternative is [s.strip('\'') for s in a.strip('[]').split(', ')] This will fall over if xyz or abc include any of the characters your stripping/splitting on (e.g if xyz is actually To be or not to be, that is the question). Unless you can guarantee they won't, you'll need to write (or rather use) a parser that understands the syntax. Iain Thinking about this some more; could the string module not use a simple tokenizer method? I know that relentlessly adding features to built-ins is a bad idea, so I'm not sure if this falls within batteries-included, or is actually just adding bulk. On the one hand, it's not difficult to write a simple state-based token parser yourself, but on the other it is also quite easy to include a pile of bugs when you do. By simple I mean something like: def tokenize(string, delim, closing_delim=None, escape_char=None) which would return a list (or a generator) of all the parts of the string enclosed by delim (or which begin with delim and end with closing_delim if closing_delim is set), ignoring any delimiters which have been escaped by escape_char. Throw an exception if the string is malformed? (odd number of delimiters, or opening/closing delims don't match) In the OP's case, he could get what he want's with a simple: l = a.tokenize(') Slippery slope, though, to nested delimiters, and XML after that. Where does shlex get us? Do we want to parse ['xyz', 'abc', ['def','ghi']] any special way? Are there security concerns past a really low complexity level, such as recursion overflows? -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
Girish wrote: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Do you want: (1) Specifically to vivify lists formatted as in your example? If so, why? (2) To save and restore arbitrary python objects? (3) To define some kind of configuration file format that you can read from Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: String To List
On Mar 17, 10:26 am, Jeff Schwab [EMAIL PROTECTED] wrote: Girish wrote: I have a string a = ['xyz', 'abc'].. I would like to convert it to a list with elements 'xyz' and 'abc'. Is there any simple solution for this?? Do you want: (1) Specifically to vivify lists formatted as in your example? If so, why? (2) To save and restore arbitrary python objects? (3) To define some kind of configuration file format that you can read from Python? Bar says: Announce your intentions, then contents. (Form, then contents.) == List of two strings. How does that go into code? list([str,str]) [type 'str', type 'str'] -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
On 5 Nov 2006 04:34:32 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? ?? I want to convert this into a python tuple of numbers ?? Do you want a python tuple with those numbers ie (1,2, 3,4), or a direct evaluation giving a tuple of tuples with those numbers, ie ((1,2), (3,4)) If the former then: a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', [] for c in a.split(','): ... try: ... c = c.replace('(','').replace(')','') ... if '.' in c: l.append(float(c)) ... else: l.append(int(c)) ... except: pass ... tuple(l) (1, 2, 3, 4, -5, -6, 12, -13, 0.10001, 0.20001) Its not so good with floats, but if you are only expecting integers you can use. a, l = '((1,2), (3,4), (-5,-6),(12,-13), (a,b), (0.1,0.2))', [] for c in a.split(','): ... try: l.append(int(c.replace('(','').replace(')',''))) ... except: pass ... tuple(l) (1, 2, 3, 4, -5, -6, 12, -13) HTH :) -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] skrev: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. I think your question is deeper and more natural than is clear from the many recepies given so far in this thread, so I'll take on another point of view, From a language design perspective, there is no reason why not the parsing capacity of the Python interpreter would be accessible in a modular fashion to the user/programmer. E.g used like this: I an imaginable Python, define you expect for an answer. In this case: (1) # import junctions, types from maybefuture:-) string = ((1,2), (3,4)) type a = tuple a | int myTuple = eval(string, goal=a) Obviously, if you expect _only_ the given form, then this might be better: (2) # import types from maybefuture:-) type a = ((int,int),(int,int)) myTuple = eval(string, goal=a) Note the use of a a|b in line 2 (I think Perl 6 is among the few programming languages giving a reasonable semantics to junctions so far). Version 2 above sholud not be a big addition to Python conceptually. Motivation: It is easy to think clearly about. It makes it easier to use eval safely and makes code more readable. This is a topic of interest to me, so feel free to post either on list or directly to me. Thanks/Henning -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? Thanks. Suresh s = '((1,2), (3,4))' separators = re.compile ('\(\s*\(|\)\s*,\s*\(|\)\s*\)') tuple ([(float (n[0]), float (n[1])) for n in [pair.split (',') for pair in separators.split (s) if pair]]) ((1.0, 2.0), (3.0, 4.0)) Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? Thanks. Suresh Pyparsing comes with an example that parses strings representing lists. Here's that example, converted to parsing only tuples of numbers. Note that this does not presume that tuples are only pairs, but can be any number of numeric values, nested to any depth, and with arbitrary whitespace, etc. This grammar also includes converters by type, so that ints come out as ints, and floats as floats. (This grammar doesn't handle empty tuples, but it does handle tuples that include an extra ',' after the last tuple element.) -- Paul Download pyparsing at http://sourceforge.net/projects/pyparsing/ . from pyparsing import * integer = (Word(nums)|Word('-+',nums)).setName(integer) real = Combine(integer + . + Optional(Word(nums))).setName(real) tupleStr = Forward().setName(tuple) tupleItem = real | integer | tupleStr tupleStr ( Suppress(() + delimitedList(tupleItem) + Optional(Suppress(,)) + Suppress()) ) # add parse actions to do conversion during parsing integer.setParseAction( lambda toks: int(toks[0]) ) real.setParseAction( lambda toks: float(toks[0]) ) tupleStr.setParseAction( lambda toks: tuple(toks) ) s = '((1,2), (3,4), (-5,9.2),)' print tupleStr.parseString(s)[0] Gives: ((1, 2), (3, 4), (-5, 9.1993)) -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. here's yet another approach: http://online.effbot.org/2005_11_01_archive.htm#simple-parser-1 also see: http://online.effbot.org/2005_11_01_archive.htm#simple-parser-3 /F -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type help, copyright, credits or license for more information. s = '((1,2), (3,4))' s = filter(lambda char: char not in ')(', s) s '1,2, 3,4' s = s.split(',') s ['1', '2', ' 3', '4'] s = map(float, s) s [1.0, 2.0, 3.0, 4.0] t1 = s[::2] t1 [1.0, 3.0] t2 = s[1::2] t2 [2.0, 4.0] zip(t1, t2) [(1.0, 2.0), (3.0, 4.0)] Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
Peter, Thanks. This recipe fails when negative numbers are used. safe_eval('(12, -12)') *** Unsafe_Source_Error: Line 1. Unsupported source construct: compiler.ast.UnarySub But, I think it could be easily fixed for somebody who understands the script. Can somebody help. Thanks. Suresh Peter Otten wrote: [EMAIL PROTECTED] wrote: I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: Hi, I have a string '((1,2), (3,4))' and I want to convert this into a python tuple of numbers. But I do not want to use eval() because I do not want to execute any code in that string and limit it to list of numbers. Is there any alternative way? This is a possibile solution, no input errors are taken into account: s = '((1,2), (3,4), (-5,9.2))' from string import maketrans tab = maketrans((), , *4) s.translate(tab) ' 1 23 4-5 9.2 ' l = s.translate(tab).split() l ['1', '2', '3', '4', '-5', '9.2'] l2 = map(float, l) l2 [1.0, 2.0, 3.0, 4.0, -5.0, 9.1993] # This is partition(l2, 2) [l2[i:i+2] for i in xrange(0, len(l2), 2)] [[1.0, 2.0], [3.0, 4.0], [-5.0, 9.1993]] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: string to list of numbers conversion
[EMAIL PROTECTED] wrote: This recipe fails when negative numbers are used. safe_eval('(12, -12)') *** Unsafe_Source_Error: Line 1. Unsupported source construct: compiler.ast.UnarySub But, I think it could be easily fixed for somebody who understands the script. I think that somebody could be you. Can somebody help. Start with class SafeEval(object): # ... def visitUnarySub(self, node, **kw): return -node.expr.value and then add some error handling. Peter -- http://mail.python.org/mailman/listinfo/python-list