Reputation: 198
I am trying to iterate through a list of several words. If a certain letter is present it will replace that letter and add a word to the existing word. But it will only work on words in the list that have that letter.
list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
#list2 = list(x+'sample' for x in cards)
or
for x in cards:
if 's' in x:
cards.append('ample')[0]
This will add 'sample' to everything, i dont know how to make it only add 'sample' to cells with the letter "s".
list1 = [06h', '12d', '05h', '04s', '12s', '12c']
if "s" in list1:
Should show
list2 = [06h', '12d', '05h', '04sample', '12sample', '12c']
Upvotes: 1
Views: 842
Reputation: 1
map(lambda x: x.replace('s','sample'), list1)
would work as well. map applies a function to every element of a list and returns a list of the results.
Python is full of tools for working with lists.
Upvotes: 0
Reputation: 2338
list2 =[]
for x in list1:
if 's' in x:
x = x.replace('s', 'sample')
list2.add(x)
Upvotes: 0
Reputation: 32003
you can use find and can replace with samples
list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
l2=[]
for item in list1:
if item.find('s'):
l2.append(item.replace('s','samples'))
else:
l2.append(item)
print(l2)
['06h', '12d', '05h', '04samples', '12samples', '12c']
Upvotes: 0
Reputation: 42678
Use a comprehension checking if the strings ends in s
:
>>> list1 = ['06h', '12d', '05h', '04s', '12s', '12c']
>>> [x + 'ample' if x.endswith('s') else x for x in list1]
['06h', '12d', '05h', '04sample', '12sample', '12c']
Upvotes: 2