Python Forum
How to reliably split string containing multiple sqlite statements?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to reliably split string containing multiple sqlite statements?
#1
Hello,

Is there a way to reliably split a string containing multiple sqlite statements?

str.split(sep=None, maxsplit=-1) does not always work -
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> sql = "select 'abc'; select 'def'; select 'annoying semicolon ;'"
>>> sql.split(';')
["select 'abc'", " select 'def'", " select 'annoying semicolon ", "'"]
>>> 
I was hoping to have something like -

["select 'abc'", " select 'def'", " select 'annoying semicolon ;'"]
Reply
#2
split of ';' should work just fine.
or perhaps "';"
>>> sql = "select 'abc'; select 'def'; select 'annoying semicolon ;'"
>>> sql.split("';")
["select 'abc", " select 'def", " select 'annoying semicolon ;'"]
>>> for n, item in enumerate(newsql):
...     if 'select' in item:
...         newitem = f"{item.strip()}';"
...     newsql[n] = newitem
... 
>>> newsql
["select 'abc';", "select 'def';", "select 'annoying semicolon ;'';"]
>>>
almost right
Reply
#3
@Larz60+ Your solution works perfectly for the example I gave - but not in general. Consider the following 3 statements-

>>> sql = "select 123; select 'def'; select 'annoying semicolon ;'"
>>> sql.split("';")
["select 123; select 'def", " select 'annoying semicolon ;'"]
>>> 
After the split there are only 2 items in the list
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,486 Aug-13-2023, 01:57 AM
Last Post: Skaperen
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,122 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  splitting file into multiple files by searching for string AlphaInc 2 882 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  [split] Parse Nested JSON String in Python mmm07 4 1,521 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Split string using variable found in a list japo85 2 1,295 Jul-11-2022, 08:52 AM
Last Post: japo85
  Matching multiple parts in string fozz 31 6,250 Jun-13-2022, 09:38 AM
Last Post: fozz
  Multiple Loop Statements in a Variable Dexty 1 1,201 May-23-2022, 08:53 AM
Last Post: bowlofred
  Search multiple CSV files for a string or strings cubangt 7 8,004 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  Split single column to multiple columns SriRajesh 1 1,319 Jan-07-2022, 06:43 PM
Last Post: jefsummers
  Split string knob 2 1,868 Nov-19-2021, 10:27 AM
Last Post: ghoul

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020