Last active
January 19, 2019 22:56
-
-
Save CallumHoward/6d44d968e4c2a2ec7fbdc76ea947161c to your computer and use it in GitHub Desktop.
Splitting escapes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# escape_splitter.py | |
# Callum Howard, 2019 | |
escapes = {r'\a', r'\b', r'\f', r'\n', r'\r', r'\t', r'\v', r'\\', r"\'", r'\"', r'\?'} | |
def split_on_escape(input, prefix=''): | |
digraphs = [''.join(pair) for pair in zip(input, input[1:])] | |
for i, digraph in enumerate(digraphs): | |
if digraph in escapes: | |
return [prefix + input[:i]] + split_on_escape(input[i+2:], prefix=digraph) | |
return [prefix + input] | |
def split_on_escape1(input): | |
result = [] | |
prefix = '' | |
skip = 0 | |
digraphs = [''.join(pair) for pair in zip(input, input[1:])] | |
for i, digraph in enumerate(digraphs): | |
if skip > 0: | |
skip -= 1 | |
continue | |
if digraph not in escapes: | |
prefix += input[i] | |
else: | |
result.append(prefix) | |
prefix = digraph | |
skip = 1 | |
if skip == 0: | |
prefix += input[-1] | |
result.append(prefix) | |
return result | |
# tests | |
f = split_on_escape1 | |
print(f(r'Hello\nworld')) | |
assert(f(r'Hello\nworld') == ['Hello', r'\nworld']) | |
print(f(r'\nHello world')) | |
assert(f(r'\nHello world') == ['', r'\nHello world']) | |
print(f(r'Hello world\n')) | |
assert(f(r'Hello world\n') == [r'Hello world', r'\n']) | |
print(f(r'Hell\o\nworld')) | |
assert(f(r'Hell\o\nworld') == [r'Hell\o', r'\nworld']) | |
print(f(r'Hello\\nworld')) | |
assert(f(r'Hello\\nworld') == ['Hello', r'\\nworld']) | |
print(f(r'Hello\nworld\nfoo\nbar\nbaz')) | |
assert(f(r'Hello\nworld\nfoo\nbar\nbaz') == | |
['Hello', r'\nworld', r'\nfoo', r'\nbar', r'\nbaz']) |
Author
CallumHoward
commented
Jan 19, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment