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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
elements = ['%{0}%'.format(element) for element in elements]
Method 2
You can use list comprehension:
elements = ["%" + e + "%" for e in elements]
Method 3
You can use list comprehensions:
elements = ["%{}%".format(element) for element in elements]
Method 4
Python 3.6+ version (f-strings):
elements = [f'%{e}%' for e in elements]
Method 5
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.
Method 6
elements = map(lambda e : "%" + e + "%", elements)
Method 7
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_)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0