简体   繁体   中英

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

please help. not sure what command to use

Use python's built-in replace() function. For the last part, if it's always 5 characters you can easily exclude them:

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

Replace _T00 to ''

For example, 'Parent=transcript:Zm00001d034962_T001' will get replaced as 'Zm00001d0349621' .

The ending string 1 from _T001 will get concatenated to 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:

['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.

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