-3

编程新手,需要了解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';
 }
4

1 回答 1

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-finto的形式扩展范围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)
于 2013-09-11T12:25:15.097 回答