+ -
当前位置:首页 → 问答吧 → 字符串查找并插入问题

字符串查找并插入问题

时间:2011-03-22

来源:互联网

比如 我有一段字符串 str = "adfasdfasdfwe23412hsrhs%$%@#@fs34zsd2fsa2sad"\
我想在其中查找 "a" 和 "2"  并在其前面添加 "-" 字符

我写的代码是
def find_str(string):
   
    pos = -2
    while True:
        pos = string.find("a", pos+2)
        if pos < 0:
            break
        string = string[:pos] + "-" + string[pos:]

    pos = -2
    while True:
        pos = string.find("2", pos+2)
        if pos < 0:
            break
        string = string[:pos] + "-" + string[pos:]
    return string

我想问的是 有其他更简单的办法吗, 可不可以去掉一个while循环,或者用其他好的办法处理
我对python不是很熟悉,不过对shell比较熟悉

作者: chenbin200818   发布时间: 2011-03-22

没有回复啊

作者: chenbin200818   发布时间: 2011-03-22