You were quite close, this is how I would've done it:

result = "('%s')" % "','".join(mylist)
Answer from Daniel Figueroa on Stack Overflow
๐ŸŒ
Python Guides
pythonguides.com โ€บ how-to-get-string-values-from-list-in-python
How To Get String Values From List In Python
September 30, 2025 - If your list contains strings mixed with numbers inside them, you can use the re module (regular expressions). ... import re # Sample list with mixed values data = ["Python3", "AI2025", 100, "DataScience", "123", "USA"] # Extract only pure strings (letters only) only_strings = [item for item in data if isinstance(item, str) and re.match("^[A-Za-z]+$", item)] print("Extracted Strings:", only_strings)
๐ŸŒ
YouTube
youtube.com โ€บ pythonguides
How to Extract String From List in Python | Python Get String From List | Python Beginner Tutorial - YouTube
In this Python tutorial, you will learn how to extract strings from a list in Python using the indexing, slicing and list comprehension methods.Indexing is a...
Published ย  April 19, 2024
Views ย  142
Top answer
1 of 5
6

Use ast.literal_eval:

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux
   import ast
   input = "[[1,2,3],['c',4,'r']]"
   output = ast.literal_eval(input)
   output
=> [[1, 2, 3], ['c', 4, 'r']]

If you actually meant for c and r to just be the current values of the variables c and r rather than the literals 'c' and 'r', you'd need to use eval, which is rather unsafe, but otherwise works the same way.

2 of 5
2

if ast.literal_eval is not sufficient and c and r are meant to be non-trivial data objects that should be interpreted, you might consider using asteval (https://github.com/newville/asteval). It can handle evaluating python strings beyond literal strings, including its own symbol table, and avoiding many of the known exploits with using eval().

asteval works like a sand-boxed mini-interpreter with a simple, flat namespace. You would have to add values for c and r to the asteval interpreter, but an example might be:

from asteval import Interpreter
aeval = Interpreter()
aeval('c = 299792458.0')   # speed of light?
aeval('r = c/(2*pi)')      # radius of a circle of circumference c?
                           # note that pi and many other numpy
                           # symbols and functions are built in
input_string = "[[1,2,3],[c,4,r]]"

out = aeval(input_string)
print(out)

which will give

[[1, 2, 3], [299792458.0, 4, 47713451.59236942]]

Alternatively, you could have set c directly from Python with

aeval.symtable['c'] = 299792458.0

There are many known-to-be-unsafe things that asteval refuses to do, but there are also many things it can do that ast.literal_eval cannot. Of course, if you're accepting code from user input, you should be very careful.

๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Extract, Replace, Convert Elements of a List in Python | note.nkmk.me
May 8, 2023 - In Python, list comprehensions allow you to create a new list by extracting, removing, replacing, or converting elements from an existing list based on specific conditions. ... The sample code in this article uses the following list as an example. l = list(range(-5, 6)) print(l) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] ... Refer to the following article for examples involving lists of strings.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ extract-list-of-substrings-in-list-of-strings-in-python
Extract List of Substrings in List of Strings in Python - GeeksforGeeks
July 23, 2025 - List comprehension is a concise and powerful way to create lists in Python. It can be employed to extract substrings based on certain conditions or patterns. The following example demonstrates how to extract all substrings containing a specific keyword: ... string_list = ["apple", "banana", "cherry", "date"] keyword = "an" result = [substring for substring in string_list if keyword in substring] print(result)
๐ŸŒ
Know Program
knowprogram.com โ€บ home โ€บ how to extract an element from a list in python
How to Extract an Element from a List in Python - Know Program
March 16, 2022 - In the program below we extract the elements which are divisible by 3 that is by using for and if loop we find mod of 3 and then print the elements. list = [3, 6, 49, 12, 18] for i in list: if i % 3 == 0: print(i) ... To get the last element ...
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ list โ€บ python-data-type-list-exercise-102.php
Python: Extract specified size of strings from a give list of string values - w3resource
# Define a function 'extract_string' that extracts strings of a specified length from a list def extract_string(str_list1, l): # Use a list comprehension to filter strings in 'str_list1' with a length of 'l' result = [e for e in str_list1 if len(e) == l] return result # Create a list 'str_list1' containing strings str_list1 = ['Python', 'list', 'exercises', 'practice', 'solution'] # Print a message indicating the original list print("Original list:") # Print the contents of 'str_list1' print(str_list1) # Set the value of 'l' to 8 l = 8 # Print a message indicating the length of the string to e
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ 5 easy ways to extract elements from a python list
5 Easy Ways To Extract Elements From A Python List - AskPython
December 29, 2021 - Here, we created a variable named โ€˜varaโ€™ and we filled the elements into the list. Then we used โ€˜varxโ€™ variable to specify the enumerate function to search for โ€˜1,2,5โ€™ index positions. vara=["10","11","12","13","14","15"] print([varx[1] for varx in enumerate(vara) if varx[0] in [1,2,5]]) ... You can also Extract Elements From A Python List using loops.
Find elsewhere
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-42720.html
extract an element of a list into a string
August 23, 2024 - Newbie here, just trying to figure some things out. every time I search on how to do something, i try it and it doesnt work. I dont get it. anyway, i have a string, x = 'a,b,c,d,e,f' that I convert to a list; a = x.split(',') gives ['a','b','c','d...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ python-extract-string-elements-from-mixed-matrix
Python โ€“ Extract String elements from Mixed Matrix
September 8, 2021 - When it is required to extract string elements from mixed matrix, a list comprehension and the โ€˜isinstanceโ€™ method is used. ... my_list = [[35, 66, 31], ["python", 13, "is"], [15, "fun", 14]] print("The list is :") print(my_list) my_result = [element for index in my_list for element in index if isinstance(element, str)] print("The result is :") print(my_result)
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 47191365 โ€บ extract-strings-from-list
python - extract strings from list - Stack Overflow
g = json_graph.node_link_graph(json.load(open("MPLS-topo.json"))) paths = nx.shortest_path(g, "H1", weight="weight") for dest in paths.keys(): # Nicely output all those paths if dest == "H2": print "Shortest Path from H1 to {} is:".format(dest) print "{}".format(paths[dest]) ... 'u' is not a string, its signaling that it is Unicode encoded. This could help you: docs.python.org/2/howto/unicode.html ... don't worry about the u. It does not affect the string operations you can do, and it won't appear in a file if you decide to write the list to a file.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-program-to-extract-characters-in-given-range-from-a-string-list
Python program to extract characters in given range from a string list - GeeksforGeeks
July 15, 2025 - Iterate through each string in the given list 'test_list' using a for loop. Use the '+= operator' to concatenate each string with the 'result' variable. Use string slicing to get the desired characters from the concatenated string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ extract-substrings-from-a-list-into-a-list-in-python
Extract Substrings From A List Into A List In Python - GeeksforGeeks
July 23, 2025 - List comprehension is a concise and elegant way to create lists in Python. It also proves to be effective for extracting substrings from a list. This approach utilizes a compact syntax to iterate through the elements of the original_list and extracts the first three characters from each string.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-extract-string-elements-from-mixed-matrix
Python - Extract String elements from Mixed Matrix - GeeksforGeeks
April 30, 2023 - In this, we iterate nested lists using list comprehension and check for string instance using isinstance(). ... # Python3 code to demonstrate working of # Extract String elements from Mixed Matrix # Using list comprehension + isinstance() # initializing lists test_list = [[5, 6, 3], ["Gfg", 3, "is"], [9, "best", 4]] # printing original list print("The original list : " + str(test_list)) # strings are extracted using isinstance() res = [ele for sub in test_list for ele in sub if isinstance(ele, str)] # printing result print("The String instances : " + str(res))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-extract-numbers-from-list-of-strings
Python โ€“ Extract numbers from list of strings | GeeksforGeeks
January 30, 2025 - Python is renowned for its simplicity and versatility, making it a popular choice for various programming tasks. When working with lists, one common requirement is to extract substrings from the elements of the list and organize them into a new list. In this article, we will see how we can extract s ... We are given a string and we have to determine how many numeric characters (digits) are present in the given string.
Top answer
1 of 2
3

If the format is exactly the same you've provided, you'd better go with using re:

import re

file_info = ['{file:file1, directory:dir1}', '{file:file2, directory:directory2}']

pattern = re.compile(r'\w+:(\w+)')
for item in file_info:
    print re.findall(pattern, item)

or, using string replace(), strip() and split() (a bit hackish and fragile):

file_info = ['{file:file1, directory:dir1}', '{file:file2, directory:directory2}']

for item in file_info:
    item = item.strip('}{').replace('file:', '').replace('directory:', '')
    print item.split(', ')

both code snippets print:

['file1', 'dir1']
['file2', 'directory2']

If the file_info items are just dumped json items (watch the double quotes), you can use json to load them into dictionaries:

import json

file_info = ['{"file":"file1", "directory":"dir1"}', '{"file":"file2", "directory":"directory2"}']

for item in file_info:
    item = json.loads(item)
    print item['file'], item['directory']

or, literal_eval():

from ast import literal_eval

file_info = ['{"file":"file1", "directory":"dir1"}', '{"file":"file2", "directory":"directory2"}']

for item in file_info:
    item = literal_eval(item)
    print item['file'], item['directory']

both code snippets print:

file1 dir1
file2 directory2

Hope that helps.

2 of 2
0

I would do:

import re

regx = re.compile('{\s*file\s*:\s*([^,\s]+)\s*'
                  ','
                  '\s*directory\s*:\s*([^}\s]+)\s*}')

file_info = ['{file:C:\\samples\\123.exe, directory  :  C:\\}',
             '{  file:  C:\\samples\\345.exe,directory:C:\\}'
             ]

for item in file_info:
    print '%r\n%s\n' % (item,
                        regx.search(item).groups())

result

'{file:C:\\samples\\123.exe, directory  :  C:\\}'
('C:\\samples\\123.exe', 'C:\\')

'{  file:  C:\\samples\\345.exe,directory:C:\\}'
('C:\\samples\\345.exe', 'C:\\')
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ extract-numbers-from-list-of-strings-in-python
Extract numbers from list of strings in Python
May 5, 2020 - import re mixed_strings = ['abc123def', ... : [123, 456789, 42] Use split() for simple separator-based extraction, isnumeric() for mixed character strings, and regular expressions for complex pattern matching....