Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform a string operation for every element in a Python list

I have a list of strings in Python - elements. I would like to edit each element in elements. See the code below (it doesn't work, but you'll get the idea):

for element in elements:     element = "%" + element + "%" 

Is there a way to do this?

like image 649
locoboy Avatar asked Aug 19 '11 20:08

locoboy


People also ask

How do you apply a function to all elements in a list Python?

Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.

Which operation in Python can access each element of the list?

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.

How do I join a list of elements into a string?

If you want to concatenate a list of numbers ( int or float ) into a single string, apply the str() function to each element in the list comprehension to convert numbers to strings, then concatenate them with join() .

How do I turn a list into a string 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.


1 Answers

elements = ['%{0}%'.format(element) for element in elements] 
like image 198
JBernardo Avatar answered Sep 19 '22 23:09

JBernardo