当前位置: 动力学知识库 > 问答 > 编程问答 >

python: how to replace a string in a list of string with a list of strings?

问题描述:

okay here is the example:

data = ['This', 'is', 'a', 'test', 'of', 'the', 'list']

replaceText = 'test'

replaceData =['new', 'test']

i did data.replace(replaceText, replaceData) but it doesn't work. How to replace a string in a list of string with a list of strings? Any help will be appreciated.

Edit:

The exact condition is to replace or split the words that contain "s" so I put a loop in it. So the end result will print

data = ['Thi', 'i', 'a', 'te','t', 'of', 'the', 'li','t']

网友答案:

In a list, find the position of text with .index(), then replace by using slice assignment:

pos = data.index(replaceText)
data[pos:pos+1] = replaceData

This will replace only one occurrence of replaceText at a time. Demo:

>>> data = ['This', 'is', 'a', 'test', 'of', 'the', 'list']
>>> replaceText = 'test'
>>> replaceData =['new', 'test']
>>> pos = data.index(replaceText)
>>> data[pos:pos+1] = replaceData

To replace all occurences, use pos plus the length of replaceData to skip searching past the previous match:

pos = 0
while True:
    try:
        pos = data.index(replaceText, pos)
    except ValueError:
        break
    data[pos:pos+1] = replaceData
    pos += len(replaceData)

If you need to loop over data while modifying it, use a copy instead:

for n in data[:]:
    # maniplate data
网友答案:

You can use list's index() method to find the position p of replaceText:

p = data.index(replaceText)

and then use the construct

data[start:end] = another_list

to replace elements from p to p+1 (end is not inclusive) with replaceData:

data[p:p+1] = replaceData

Note that index() throws ValueError if replaceText does not exist in data:

try:
  p = data.index(replaceText)
  data[p:p+1] = replaceData
except ValueError:
  # replaceText is not present in data, handle appropriately.
网友答案:

yah, the actually condition needs me to replace or split any string that contains the character 's', say 'test' will be replaced by 'te' and 't' to the list

from itertools import chain
data = ['This', 'is', 'a', 'test', 'of', 'the', 'list']
>>> filter(None, chain.from_iterable(el.split('s') for el in data))
['Thi', 'i', 'a', 'te', 't', 'of', 'the', 'li', 't']
分享给朋友:
您可能感兴趣的文章:
随机阅读: