简体   繁体   中英

How to replace parts of strings in a list

i am not so familiar with python, and i don't know how to do this.. So I have a list that looks like this:

animal_id = ['id01', 'id02', 'id03', 'id04', 'id05']

and I would like to make a new list from the list above, using string manipulation. and the new list should look like this:

animal_list = ['a01', 'a02', 'a03', 'a04', 'a05']

i think i would have to make a for loop, but i dont know what methods (in string) to use to achieve the desired output

By replacing 'id' for an 'a' in every item of the list, and creating a list containing these items.

animal_id = ['id01', 'id02', 'id03', 'id04', 'id05']

animal_list = [i.replace('id','a') for i in animal_id]

print(animal_list)

Output:

['a01', 'a02', 'a03', 'a04', 'a05']

Use a list-comprehension:

animal_id = ['id01', 'id02', 'id03', 'id04', 'id05']

animal_list = [f'a{x[2:]}' for x in animal_id]
# ['a01', 'a02', 'a03', 'a04', 'a05']

You can use list comprehension and str.replace() to change id to a

animal_list = [i.replace('id', 'a') for i in animal_id]
# ['a01', 'a02', 'a03', 'a04', 'a05']

Expanded:

animal_list = []
for i in animal_id:
    i = i.replace('id', 'a')
    animal_list.append(i)

Try this !

I iterate the loop till the size of animal_id & split the each element of animal_id with the 'id'. After splitting, it returns the digits value & then concatenate the digits with 'a'.

Code :

animal_id = ['id01', 'id02', 'id03', 'id04', 'id05']
for i in range(0,len(animal_id)):
    animal_id[i]='a' + animal_id[i].split("id")[1]
print(animal_id)

Output :

['a01', 'a02', 'a03', 'a04', 'a05'] 

create a new list and append to it using string indexing chosing only the last 2 char from original list items

new_animal = []
for item in animal_id:
    new_animal.append('a'+ item[-2:])
new_animal

['a01', 'a02', 'a03', 'a04', 'a05']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM