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?
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.
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.
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.
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.
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.
In Python 3.6 you could write:
markers = [(97,64),(45,84)] result = ''.join(f'&markers={pair}' for pair in markers) return result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With