仅处理对象的直接翻译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
into的形式扩展范围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)