E.Kim
E.Kim

Reputation: 21

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

Upvotes: 0

Views: 17585

Answers (5)

Usman
Usman

Reputation: 2029

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'] 

Upvotes: 1

PepeGonza
PepeGonza

Reputation: 86

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']

Upvotes: 6

vash_the_stampede
vash_the_stampede

Reputation: 4606

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)

Upvotes: 1

Austin
Austin

Reputation: 26037

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']

Upvotes: 1

Khalil Al Hooti
Khalil Al Hooti

Reputation: 4526

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']

Upvotes: 0

Related Questions