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']
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']
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']
list2 =[]
for x in list1:
if 's' in x:
x = x.replace('s', 'sample')
list2.add(x)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.