Created
February 2, 2020 02:43
-
-
Save nraw/7fa36abad53145ffb4a4255fbf16a049 to your computer and use it in GitHub Desktop.
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
import re | |
def remove_leading_whitespace(text): | |
leading_whitespace_match = re.match(r'(^[^\S\n]*)\w', text) | |
if leading_whitespace_match is not None: | |
leading_whitespace = leading_whitespace_match[1] | |
else: | |
return text | |
num_spaces = len(leading_whitespace) | |
needs_correction = True | |
lines = text.split('\n') | |
full_text = '' | |
for line in lines: | |
if needs_correction and line[:num_spaces] == leading_whitespace: | |
adjusted_line = line[num_spaces:] | |
elif not line: # should first remove all whitespace though | |
adjusted_line = line | |
else: | |
needs_correction = False | |
adjusted_line = line | |
full_text = full_text + adjusted_line + '\n' | |
return full_text | |
def test_normal_stays(): | |
text = 'a = 5' | |
expected_text = text | |
assert expected_text == remove_leading_whitespace(text) | |
text = ''' | |
a = 1 | |
b = 2 | |
def c(): | |
return 4 | |
''' | |
print(text) | |
print(remove_leading_whitespace(text)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment