繁体   English   中英

如何替换 python 列表中字符串中的某些部分?

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

这就是它的样子。

我想替换Parent=transcript:_T00

请帮忙。 不确定使用什么命令

使用 python 的内置replace() function。 对于最后一部分,如果总是 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

我假设您想将以下字符串替换为''

Parent=transcript:替换为''

_T00替换为''

例如, 'Parent=transcript:Zm00001d034962_T001'将被替换为'Zm00001d0349621'

_T001的结尾字符串1将连接到Zm00001d034962

如果这是您的预期结果,则代码为:

new_list = [x.replace('Parent=transcript:','').replace('_T00','') for x in input_list]
print (new_list)

new_list 的new_list将是:

['Zm00001d0349621', 'Zm00001d0349622', 'Zm00001d0349623', 'Zm00001d0349623', 'Zm00001d0349624', 'Zm00001d0349625', 'Zm00001d0349625', 'Zm00001d0349625']

请注意,您可以将''替换为您想要的新字符串。 我已将其标记为'' ,因为我不知道您的新替换字符串将是什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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