473,789 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to Split a String

Hi,

I need to convert the string: '(a, b, "c", d, "e")' into the following
list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually
use the split function, but this mini-monster wouldn't properly get
split up due to those random quotations postgresql returns to me.

Please help me with this,
Thanks,
Sia
Nov 29 '07 #1
12 1978
Siah wrote:
I need to convert the string: '(a, b, "c", d, "e")' into the
following list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader
does. I usually use the split function, but this mini-monster
wouldn't properly get split up due to those random quotations
postgresql returns to me.
I heavily suggest you to look at the docs -- those are very basic
functions.

http://docs.python.org/lib/string-methods.html

One solution might be:
>>results = []
for part in '(a, b, "c", d, "e")'.split("," ):
.... part = part.strip()
.... part = part.strip("(), \"")
.... part = part.strip()
.... results.append( part)
....
>>print results
['a', 'b', 'c', 'd', 'e']
>>>
Regards,
Björn
--
BOFH excuse #285:

Telecommunicati ons is upgrading.

Nov 29 '07 #2
On 2007-11-29, Siah <si*********@gm ail.comwrote:
I need to convert the string: '(a, b, "c", d, "e")' into the following
list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does.
http://docs.python.org/lib/module-csv.html

--
Grant Edwards grante Yow! ... the HIGHWAY is
at made out of LIME JELLO and
visi.com my HONDA is a barbequeued
OYSTER! Yum!
Nov 29 '07 #3
I need to convert the string: '(a, b, "c", d, "e")' into the
following list ['a', 'b', 'c', 'd', 'e']. Much like a csv
reader does. I usually use the split function, but this
mini-monster wouldn't properly get split up due to those
random quotations postgresql returns to me.
Uh...use the csv reader? :) No need to reinvent the parsing wheel.
>>import csv
from StringIO import StringIO
s = 'a,b,"c",d,"e"'
csv.reader(St ringIO(s)).next ()
['a', 'b', 'c', 'd', 'e']

If you really have the parens in your string too, you can peal
them off first with "s[1:-1]"
>>s = '(a,b,"c",d,"e" )'
csv.reader(St ringIO(s[1:-1])).next()
['a', 'b', 'c', 'd', 'e']

or strip any/all parens:
>>s = '(a,b,"c",d,"e" )'
csv.reader(St ringIO(s.lstrip ('(').rstrip(') '))).next()
['a', 'b', 'c', 'd', 'e']

-tkc
Nov 29 '07 #4
Siah ha scritto:
Hi,

I need to convert the string: '(a, b, "c", d, "e")' into the following
list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually
use the split function, but this mini-monster wouldn't properly get
split up due to those random quotations postgresql returns to me.

Please help me with this,
Thanks,
Sia
One solution:
>>s = '(a, b, "c", d, "e")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e']
Nov 29 '07 #5
The basic split/strip method wouldn't split '(a, b, "c,...", d)',
which is why I chose not to use it.

The csv solution seems to work well, that helped me much here (thank
you), but I am looking to see if I can get it solved with some regular
expression. This is how far I've come so far, but it needs much work:
re.compile('"*, "*').split( x[1:-1])

Thanks for your help,
Sia


On Nov 29, 3:24 pm, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n.. .@spamgourmet.c omwrote:
Siah wrote:
I need to convert the string: '(a, b, "c", d, "e")' into the
following list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader
does. I usually use the split function, but this mini-monster
wouldn't properly get split up due to those random quotations
postgresql returns to me.

I heavily suggest you to look at the docs -- those are very basic
functions.

http://docs.python.org/lib/string-methods.html

One solution might be:
>results = []
for part in '(a, b, "c", d, "e")'.split("," ):

... part = part.strip()
... part = part.strip("(), \"")
... part = part.strip()
... results.append( part)
...>>print results

['a', 'b', 'c', 'd', 'e']

Regards,

Björn

--
BOFH excuse #285:

Telecommunicati ons is upgrading.
Nov 29 '07 #6
On 2007-11-29, imho <ce***@comeno.i twrote:
Siah ha scritto:
>Hi,

I need to convert the string: '(a, b, "c", d, "e")' into the following
list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually
use the split function, but this mini-monster wouldn't properly get
split up due to those random quotations postgresql returns to me.

Please help me with this,
Thanks,
Sia

One solution:
>s = '(a, b, "c", d, "e")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e']
That fails when a quoted string contains commas:
>>s = '(a, b, "c", d, "e,f,g")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e', 'f', 'g']

I presume the correct result would be

['a', 'b', 'c', 'd', 'e,f,g']

--
Grant Edwards grante Yow! I wonder if I could
at ever get started in the
visi.com credit world?
Nov 29 '07 #7
On 2007-11-29, Grant Edwards <gr****@visi.co mwrote:
>One solution:
>>s = '(a, b, "c", d, "e")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e']

That fails when a quoted string contains commas:
>>>s = '(a, b, "c", d, "e,f,g")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e', 'f', 'g']

I presume the correct result would be

['a', 'b', 'c', 'd', 'e,f,g']
You can get that result easily with the csv module:
>>repr(ss)
'\'a,b,"c",d,"e ,f,g"\''
>>for row in csv.reader([ss],skipinitialspa ce=True):
.... print row
....
['a', 'b', 'c', 'd', 'e,f,g']

--
Grant Edwards grante Yow! I'm not available
at for comment..
visi.com
Nov 29 '07 #8
Thanks Mr. Edwards, I went ahead and started using the csv reader.
Sia
Nov 29 '07 #9
Grant Edwards ha scritto:
>One solution:
>>>>s = '(a, b, "c", d, "e")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e']

That fails when a quoted string contains commas:
>>>s = '(a, b, "c", d, "e,f,g")'
print [x.strip('" ') for x in s.strip('()').s plit(',')]
['a', 'b', 'c', 'd', 'e', 'f', 'g']

I presume the correct result would be

['a', 'b', 'c', 'd', 'e,f,g']
Uhm, agree. I supposed quoted strings were presumed to be 'trivial'.
Definitely csv module is the solution :-)
Nov 29 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
31181
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it will split myString up using the delimiter of 1 space so that
11
2509
by: Carlos Ribeiro | last post by:
Hi all, While writing a small program to help other poster at c.l.py, I found a small inconsistency between the handling of keyword parameters of string.split() and the split() method of strings. I wonder if someone else had ever stumbled on it before, and if it has a good reason to work like it is. Both implementations take two parameters: the separator character and the max number of splits (maxsplit). However, string.split() accept
4
5791
by: Itzik | last post by:
can i split this string string str = "aa a - bb-b - ccc" with this delimiter string del = " - " i want recieve 3 items : "aa a" , "bb-b" , "ccc"
3
9671
by: Ben | last post by:
Hi I am creating a dynamic function to return a two dimensional array from a delimeted string. The delimited string is like: field1...field2...field3... field1...field2...field3... field1...field2...field3...
5
5880
by: kurt sune | last post by:
The code: Dim aLine As String = "cat" & vbNewLine & "dog" & vbNewLine & "fox" & vbNewLine Dim csvColumns1 As String() = aLine.Split(vbNewLine, vbCr, vbLf) Dim csvColumns2 As String() = Microsoft.VisualBasic.Strings.Split(aLine, vbNewLine, -1, CompareMethod.Binary)
0
9506
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6761
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5415
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2906
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.