[英]How do I replace certain pieces in a string in a list in python?
['Parent=transcript:Zm00001d034962_T001', 'Parent=transcript:Zm00001d034962_T002', 'Parent=transcript:Zm00001d034962_T003', 'Parent=transcript:Zm00001d034962_T003', 'Parent=transcript:Zm00001d034962_T004', 'Parent=transcript:Zm00001d034962_T005', 'Parent=transcript:Zm00001d034962_T005', 'Parent=transcript:Zm00001d034962_T005']
This is what it looks like.这就是它的样子。
I would like to replace Parent=transcript:
and _T00
我想替换
Parent=transcript:
和_T00
please help.请帮忙。 not sure what command to use
不确定使用什么命令
Use python's built-in replace()
function.使用 python 的内置
replace()
function。 For the last part, if it's always 5 characters you can easily exclude them:对于最后一部分,如果总是 5 个字符,您可以轻松地排除它们:
items = [
'Parent=transcript:Zm00001d034962_T001',
'Parent=transcript:Zm00001d034962_T002',
'Parent=transcript:Zm00001d034962_T003',
'Parent=transcript:Zm00001d034962_T003',
'Parent=transcript:Zm00001d034962_T004',
'Parent=transcript:Zm00001d034962_T005',
'Parent=transcript:Zm00001d034962_T005',
'Parent=transcript:Zm00001d034962_T005'
]
# use enumerate to replace the item in the list
for index, item in enumerate(items):
# this replaces the items with an empty string, deleting it
new_item = item.replace('Parent=transcript:', '')
# this accesses all the characters in the string minus the last 5
new_item = new_item[0:len(new_item) - 5] + "whatever you want to replace that with"
# replace the item in the list
items[index] = new_item
I am assuming you want to replace the following strings to ''
我假设您想将以下字符串替换为
''
Replace Parent=transcript:
to ''
将
Parent=transcript:
替换为''
Replace _T00
to ''
将
_T00
替换为''
For example, 'Parent=transcript:Zm00001d034962_T001'
will get replaced as 'Zm00001d0349621'
.例如,
'Parent=transcript:Zm00001d034962_T001'
将被替换为'Zm00001d0349621'
。
The ending string 1
from _T001
will get concatenated to Zm00001d034962
. _T001
的结尾字符串1
将连接到Zm00001d034962
。
If that is your expected result, the code is:如果这是您的预期结果,则代码为:
new_list = [x.replace('Parent=transcript:','').replace('_T00','') for x in input_list]
print (new_list)
The output of new_list
will be: new_list 的
new_list
将是:
['Zm00001d0349621', 'Zm00001d0349622', 'Zm00001d0349623', 'Zm00001d0349623', 'Zm00001d0349624', 'Zm00001d0349625', 'Zm00001d0349625', 'Zm00001d0349625']
Note you can replace ''
with whatever you want the new string to be.请注意,您可以将
''
替换为您想要的新字符串。 I have marked it as ''
as I don't know what your new replaced string will be.我已将其标记为
''
,因为我不知道您的新替换字符串将是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.