Perform a string operation for every element in a Python list

PythonStringListString Operations

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

elements = ['%{0}%'.format(element) for element in elements]

Solution 2 - Python

You can use list comprehension:

elements = ["%" + e + "%" for e in elements]

Solution 3 - Python

You can use list comprehensions:

elements = ["%{}%".format(element) for element in elements]

Solution 4 - Python

Python 3.6+ version (f-strings):

elements = [f'%{e}%' for e in elements]

Solution 5 - Python

There are basically two ways you can do what you want: either edit the list you have, or else create a new list that has the changes you want. All the answers currently up there show how to use a list comprehension (or a map()) to build the new list, and I agree that is probably the way to go.

The other possible way would be to iterate over the list and edit it in place. You might do this if the list were big and you only needed to change a few.

for i, e in enumerate(elements):
    if want_to_change_this_element(e):
        elements[i] = "%{}%".format(e)

But as I said, I recommend you use one of the list comprehension answers.

Solution 6 - Python

elements = map(lambda e : "%" + e + "%", elements)

Solution 7 - Python

Here some more examples

char = ['g:', 'l:', 'q:']

Using Replace

for i in range(len(char)):
    char[i] = char[i].replace(':', '')

Using strip

for i in range(len(char)):
    char[i] = char[i].strip(':')

Using a function

def list_cleaner(list_):
    return [char_.strip(':') for char_ in list_]


new_char = list_cleaner(char)
print(new_char)

Using Generator function(adviced if you have a large piece of data)

def generator_cleaner(list_):
    yield from (char_.strip(':') for char_ in list_)

# Prints all results in once
gen_char = list(generator_cleaner(char))

# Prints as much as you need, in this case only 8 chars
# I increase a bit the list so it makes more sense
char = ['g:', 'l:', 'q:', 'g:', 'l:', 'q:', 'g:', 'l:', 'q:']

# let's call our Generator Function
gen_char_ = generator_cleaner(char)

# We call only 8 chars
gen_char_ = [next(gen_char_) for _ in range(8)]
print(gen_char_)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlocoboyView Question on Stackoverflow
Solution 1 - PythonJBernardoView Answer on Stackoverflow
Solution 2 - PythonAchimView Answer on Stackoverflow
Solution 3 - PythonleolukView Answer on Stackoverflow
Solution 4 - PythonZygDView Answer on Stackoverflow
Solution 5 - PythonstevehaView Answer on Stackoverflow
Solution 6 - PythonbpgergoView Answer on Stackoverflow
Solution 7 - PythonFederico BaùView Answer on Stackoverflow