[英]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:我对python不太熟悉,我不知道该怎么做..所以我有一个看起来像这样的列表:
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我想我必须做一个 for 循环,但我不知道使用什么方法(在字符串中)来实现所需的输出
By replacing 'id' for an 'a' in every item of the list, and creating a list containing these items.通过在列表的每个项目中将 'id' 替换为 'a',并创建一个包含这些项目的列表。
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
您可以使用列表中理解和str.replace()
来更改id
到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'.我迭代循环直到animal_id的大小,并将animal_id的每个元素与'id'分开。 After splitting, it returns the digits value & then concatenate the digits with 'a'.拆分后,它返回数字值,然后将数字与“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创建一个新列表并使用字符串索引附加到它,只从原始列表项中选择最后 2 个字符
new_animal = []
for item in animal_id:
new_animal.append('a'+ item[-2:])
new_animal
['a01', 'a02', 'a03', 'a04', 'a05']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.