将C函数转换为Python3形式?

时间:2013-09-11 12:01:44

标签: python c python-3.x

编程新手,需要找出python3中的以下函数是什么?

void expand (char s1 [], char s2[])
{
    char c;
    int i,j;
    i=j=0;
    while ((c=s1[i++]) != '\0')
        if (s1[i] =='-' && s1[i+1] >=c {
             i++;
             while (c<s1 [i])  
                 s2 [j++] = c++;
         }
         else
           s2 [j++] =c;
    s2 [j] = '\0';
 }

1 个答案:

答案 0 :(得分:3)

仅对byte个对象进行处理的直接翻译将是:

def expand(s1):
    i = 0
    s2 = bytearray()
    while i < len(s1):
        c = s1[i]
        i += 1
        if (i + 1) < len(s1) and s1[i] == ord(b'-') and s1[i + 1] >= c:
            i += 1
            while c < s1[i]:
                s2.append(c)
                c += 1
        else:
           s2.append(c)
    return bytes(s2)

这似乎会将a-f形式的范围扩展为abcdef

>>> expand(b'a-f')
b'abcdef'

您可以使用正则表达式执行相同的操作:

import re

_range = re.compile(rb'(.)-(.)')
def _range_expand(match):
    start, stop = match.group(1)[0], match.group(2)[0] + 1
    if start < stop:
        return bytes(range(start, stop))
    return match.group(0)

def expand(s1):
    return _range.sub(_range_expand, s1)

或者,对于unicode字符串(类型str)而不是:

import re

_range = re.compile(r'(.)-(.)')
def _range_expand(match):
    start, stop = ord(match.group(1)), ord(match.group(2)) + 1
    if start < stop:
        return ''.join([chr(i) for i in range(start, stop)])
    return match.group(0)

def expand(s1):
    return _range.sub(_range_expand, s1)