Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string from list comprehension

Tags:

python-2.7

I am trying to get this string as a result:

"&markers=97,64&markers=45,84" 

From the Python code below:

markers = [(97,64),(45,84)] result = ("&markers=%s" %x for x in markers) return result 

How do I do this as the below does not give me the actual string?

like image 681
Reno Avatar asked Apr 30 '13 14:04

Reno


People also ask

Can you use list comprehension on a string?

It can identify when it receives a string or a tuple and work on it like a list. You can do that using loops. However, not every loop can be rewritten as list comprehension. But as you learn and get comfortable with list comprehensions, you will find yourself replacing more and more loops with this elegant syntax.

Is there a string comprehension in Python?

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.

How do you return 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.

What is the syntax for list comprehension in Python?

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.


Video Answer


2 Answers

You need to join your string like this:

markers = [(97,64),(45,84)] result = ''.join("&markers=%s" % ','.join(map(str, x)) for x in markers) return result 

UPDATE

I didn't initially have the ','.join(map(str, x)) section in there to turn each tuple into strings. This handles varying length tuples, but if you will always have exactly 2 numbers, you might see gatto's comment below.

The explanation of what's going on is that we make a list with one item for each tuple from markers, turning the tuples into comma separated strings which we format into the &markers= string. This list of strings is then joined together separated by an empty string.

like image 68
underrun Avatar answered Sep 29 '22 08:09

underrun


In Python 3.6 you could write:

markers = [(97,64),(45,84)] result = ''.join(f'&markers={pair}' for pair in markers) return result 
like image 26
Pluto Avatar answered Sep 29 '22 06:09

Pluto