Python Forum
Line of file from string to list to tuple
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Line of file from string to list to tuple
#1
How do I convert a line from a file into a tuple so I can input into mysql database?
File:
Output:
['sql statement %s where id = %s', ['test','1']]
I am struggling with tuple() and list() from a string value...
I am trying to use
Output:
conn.execute(tuple[0],tuple[1])
Reply
#2
I think you may want to do some additional parsing, but as is:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> the_string = "['sql statement %s where id = %s', ['test','1']]"
>>> as_tuples = tuple(the_string.split())
but I doubt that is exactly what you want.
perhaps you could show what you would like the tuples to contain.
Reply
#3
After reading another thread and doing some testing, I think I want:
import ast
sqlback = ast.literal_eval(line)
Tuples should be:
sqlback[0] = 'sql statement %s where id = %s'
sqlback[1] = ['test','1']
sqlback[1][0] = 'test'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using > < for tuple , list,... akbarza 3 401 Feb-05-2024, 01:18 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Need to replace a string with a file (HTML file) tester_V 1 699 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Change font in a list or tuple apffal 4 2,635 Jun-16-2023, 02:55 AM
Last Post: schriftartenio
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,392 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Getting last line of each line occurrence in a file tester_V 1 812 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  how to convert tuple value into string mg24 2 2,237 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,306 Sep-27-2022, 01:38 PM
Last Post: buran
  search a list or tuple for a specific type ot class Skaperen 8 1,854 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  Inserting line feeds and comments into a beautifulsoup string arbiel 1 1,145 Jul-20-2022, 09:05 AM
Last Post: arbiel

Forum Jump:

User Panel Messages

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