+ -
当前位置:首页 → 问答吧 → python re 有没有 php里 preg_replace 这样的函数

python re 有没有 php里 preg_replace 这样的函数

时间:2010-12-16

来源:互联网

我想实现两组数对调的效果  ,比如  1对5 2对6  3对7 4对8
php里只需要
$a=array('1','2','3','4');
$b=array('5','6','7','8');
$strnow='1234';
$new=preg_replace($a,$b,$strnow);

new就是5678


但是re.sub肯定是不能这么批量实现的,怎么解决呢?

作者: rockyaow   发布时间: 2010-12-16

不知道php,没有用过,但你是要两个list交换的话:
In [1]: a = [1,2,3,4]

In [2]: b = [5,6,7,8]

In [3]: a, b = b, a

In [4]: print a, b
[5, 6, 7, 8] [1, 2, 3, 4]

作者: icyomik   发布时间: 2010-12-17

多replace几次就行了,估计没有类似的函数满足lz需求

作者: starzhestarzhe   发布时间: 2010-12-17

解决了

#!/usr/bin/env python
import re

def killher(somestr):
    if somestr.group(0) == '1':
        return '5'
    if somestr.group(0) == '2':
        return '6'
    if somestr.group(0) == '3':
        return '7'
    if somestr.group(0) == '4':
        return '8'

a='abc12x34edf'
b=re.sub('[1-4]',killher,a)
print b

作者: rockyaow   发布时间: 2010-12-17