在python中只替换列表项中第一次出现的字符?

时间:2012-09-11 01:49:47

标签: python string list replace

这很难解释,但这是我的问题..

sampleList = ['_ This is an item.','__ This is also an item']

我正在尝试使用sampleList并查找_是否仅出现在第一个字符行中,将其替换为#,然后如果出现__,则替换为{{1 }}

即使对自己来说也有点难以理解。

基本上如果我有一个列表,我希望它通过列表工作,只找到可能的dict的FIRST实例并用相应的值替换它。然后返回整个列表..

编辑:

很抱歉,如果我的描述性不够......

&

输出:

dictarray = {
'_':'&',
'__':'*#',
'____':'*$(@'
}

sampleList = ['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']

我需要能够捕获是否在项目开头找到了密钥,如果是,请将其更改为该值。

2 个答案:

答案 0 :(得分:5)

# The original input data
dictarray = {
'_':'&',
'__':'*#',
'____':'*$(@'
}

sampleList = ['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']

# Order the substitutions so the longest are first.
subs = sorted(dictarray.items(), key=lambda pair: len(pair[0]), reverse=True)

def replace_first(s, subs):
    """Replace the prefix of `s` that first appears in `subs`."""
    for old, new in subs:
        if s.startswith(old):
            # replace takes a count of the number of replacements to do.
            return s.replace(old, new, 1)
    return s

# make a new list by replace_first'ing all the strings.
new_list = [replace_first(s, subs) for s in sampleList]

print new_list

产生

['& This is an item.', '*# This is also an item', '& just another _ item', '*$(@ and this last one']

在这里,我按摩了dictarray,首先命令替换最长,这样较短的前缀不会排除较长的前缀。

答案 1 :(得分:1)

这里的诀窍是将较长的下划线(__)置于if条件下,然后将较小的下划线(_)置于elif条件下:

dic = {
'_':'&',
'__':'*#',
'____':'*$(@'
}
lis=['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']
for x in sorted(dic,key=len,reverse=True):
    for i,y in enumerate(lis):
        if y.startswith(x):
            lis[i]=y.replace(x,dic[x])

print(lis)

输出

['& This is an item.', '*# This is also an item', '& just another & item', '*$(@ and this last one']