How do you extract a string from a list in python?

Assuming a python array "myarray" contains:

mylist = [u'a',u'b',u'c']

I would like a string that contains all of the elements in the array, while preserving the double quotes like this (notice how there are no brackets, but parenthesis instead):

result = "('a','b','c')"

I tried using ",".join(mylist), but it gives me the result of "a,b,c" and eliminated the single quotes.

asked Sep 16, 2013 at 15:37

1

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

result = "('%s')" % "','".join(mylist)

answered Sep 16, 2013 at 15:42

How do you extract a string from a list in python?

Daniel FigueroaDaniel Figueroa

10k5 gold badges41 silver badges64 bronze badges

What about this:

>>> mylist = [u'a',u'b',u'c']
>>> str(tuple(map(str, mylist)))
"('a', 'b', 'c')"

answered Sep 16, 2013 at 15:41

How do you extract a string from a list in python?

arshajiiarshajii

125k24 gold badges233 silver badges279 bronze badges

Try this:

result = "({})".format(",".join(["'{}'".format(char) for char in mylist]))

answered Sep 16, 2013 at 15:42

Samy ArousSamy Arous

6,73412 silver badges20 bronze badges

>>> l = [u'a', u'b', u'c']
>>> str(tuple([str(e) for e in l]))
"('a', 'b', 'c')"

Calling str on each element e of the list l will turn the Unicode string into a raw string. Next, calling tuple on the result of the list comprehension will replace the square brackets with parentheses. Finally, calling str on the result of that should return the list of elements with the single quotes enclosed in parentheses.

answered Sep 16, 2013 at 15:43

U-DONU-DON

2,05214 silver badges14 bronze badges

What about repr()?

>>> repr(tuple(mylist))
"(u'a', u'b', u'c')"

More info on repr()

answered Sep 16, 2013 at 15:39

Diego HerranzDiego Herranz

2,7672 gold badges17 silver badges34 bronze badges

0

Here is another variation:

mylist = [u'a',u'b',u'c']
result = "\"{0}\"".format(tuple(mylist))
print(result)

Output:

"('a', 'b', 'c')"    

tima

1,4684 gold badges19 silver badges27 bronze badges

answered Sep 15, 2017 at 0:31

How do you extract a string from a list in python?

In Python, you can generate a new list by extracting, removing, replacing, or converting elements that meet the conditions of an existing list with list comprehensions.

This article describes the following contents.

  • Basics of list comprehensions
  • Apply operation to all elements of the list
  • Extract/remove elements that meet the conditions from the list
  • Replace/convert elements that meet the conditions in the list

See the following article for examples of lists of strings.

  • Extract and replace elements that meet the conditions of a list of strings in Python

It is also possible to randomly sample elements from a list.

  • Random sampling from a list in Python (random.choice, sample, choices)

Take the following list as an example.

l = list(range(-5, 6))
print(l)
# [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]

Basics of list comprehensions

In Python, you can create a list using list comprehensions. It's simpler than using the for loop.

[expression for variable_name in iterable if condition]

expression is applied to the elements that satisfy condition of iterable (list, tuple, etc.), and a new list is generated. if condition can be omitted, if omitted, expression is applied to all elements.

See the following article for details on list comprehensions.

  • List comprehensions in Python

Apply operation to all elements of the list

If you write the desired operation in the expression part of list comprehensions, that operation is applied to all the elements of the list.

l_square = [i**2 for i in l]
print(l_square)
# [25, 16, 9, 4, 1, 0, 1, 4, 9, 16, 25]

l_str = [str(i) for i in l]
print(l_str)
# ['-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5']

You can use this to convert a list of numbers to a list of strings. See the following article for details.

  • Convert a list of strings and a list of numbers to each other in Python

If you just want to select elements by condition, you do not need to process them with expression, so you can write it as follows.

[variable_name for variable_name in original_list if condition]

Only the elements that meet the conditions (elements that return True for condition) are extracted, and a new list is generated.

l_even = [i for i in l if i % 2 == 0]
print(l_even)
# [-4, -2, 0, 2, 4]

l_minus = [i for i in l if i < 0]
print(l_minus)
# [-5, -4, -3, -2, -1]

If if condition is changed to if not condition, only elements that do not meet the condition (elements that return False for condition) are extracted. This is equivalent to removing elements that meet the condition.

l_odd = [i for i in l if not i % 2 == 0]
print(l_odd)
# [-5, -3, -1, 1, 3, 5]

l_plus = [i for i in l if not i < 0]
print(l_plus)
# [0, 1, 2, 3, 4, 5]

Of course, you can specify a corresponding condition without using not.

l_odd = [i for i in l if i % 2 != 0]
print(l_odd)
# [-5, -3, -1, 1, 3, 5]

l_plus = [i for i in l if i >= 0]
print(l_plus)
# [0, 1, 2, 3, 4, 5]

You can also connect multiple conditions with or or and. Negation not can also be used.

l_minus_or_even = [i for i in l if (i < 0) or (i % 2 == 0)]
print(l_minus_or_even)
# [-5, -4, -3, -2, -1, 0, 2, 4]

l_minus_and_odd = [i for i in l if (i < 0) and not (i % 2 == 0)]
print(l_minus_and_odd)
# [-5, -3, -1]

Replace/convert elements that meet the conditions in the list

If you want to replace or convert elements that meet the condition without changing elements that do not meet the condition, use conditional expressions in the expression part of the list comprehensions.

In Python, conditional expressions can be written as follows:

X is value or expression for True, and Y is value or expression for False.

  • Conditional expressions in Python

a = 80
x = 100 if a > 50 else 0
print(x)
# 100

b = 30
y = 100 if b > 50 else 0
print(y)
# 0

Use list comprehensions and conditional expressions:

[X if condition else Y for variable_name in original_list]

The part enclosed in parentheses is conditional expressions. No parentheses are needed in the actual code.

[(X if condition else Y for variable_name) in original_list]

If you write variable_name in X or Y, the value of the original element is used as it is, and if you write some expression, that expression is applied.

l_replace = [100 if i > 0 else i for i in l]
print(l_replace)
# [-5, -4, -3, -2, -1, 0, 100, 100, 100, 100, 100]

l_replace2 = [100 if i > 0 else 0 for i in l]
print(l_replace2)
# [0, 0, 0, 0, 0, 0, 100, 100, 100, 100, 100]

l_convert = [i * 10 if i % 2 == 0 else i for i in l]
print(l_convert)
# [-5, -40, -3, -20, -1, 0, 1, 20, 3, 40, 5]

l_convert2 = [i * 10 if i % 2 == 0 else i / 10 for i in l]
print(l_convert2)
# [-0.5, -40, -0.3, -20, -0.1, 0, 0.1, 20, 0.3, 40, 0.5]

How do you pull a string out of a list in Python?

Use list. remove() to remove a string from a list. Call list. remove(x) to remove the first occurrence of x in the list.

How do you extract an element as a string from a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do I extract a specific item from a list in Python?

Use the syntax [list[index] for index in index_list] to get a list containing the elements in list at the indices in index_list ..
a_list = ["apple", "pear", "banana", "peach"].
indices = [1, 3].
extracted_elements = [a_list[index] for index in indices].