Python string parsing has quite a few edge cases. This is a string:
"a"
Putting 2 strings immediately after each other implicitly concatenates them, so this is also a string:
"a""a"
However, if you put 3 quotes in a row, it will create a "triple quoted string" which can only be ended by another 3 quotes in a row. A triple quoted string can contain other quotes. These quotes will not end the string unless there are 3 of them. Thus this is valid:
"""a"a"""
Of course, you can combine these together, so this is a valid string:
"""a""""a"
And this:
"""""aaa"""""""""
3 quotes in a row outside a string always starts a triple quoted string, even if such a string would be invalid. There is no backtracking.
A string is not valid if:
- Any
a
appears outside of a string literal (would getSyntaxError: invalid syntax
in python) OR - The end of the sequence is inside a string literal (would get
SyntaxError: unterminated string literal (detected at line 1)
in python)
Your task
Given a string containing 2 distinct characters, one representing a double quote and another representing the letter "a" (most letters except b, u, r, and f would work exactly the same, you don't need to concern yourself with that detail), determine if it would be a valid python string, or invalid syntax.
You do not need to consider single quotes or how double and single quotes normally interact.
An array of booleans or an array of bytes would also be a valid input method. Thus some valid representations for "a"
include $2$
, [0,1,0]
, or [False, True, False]
.
This is code-golf, shortest answer wins.
Test Cases
Truthy | Falsy |
---|---|
"a" (1-1) |
"a (1) |
"a""a" (1-2-1) |
"a"a" (1-1-1) |
"""a"a""" (3-1-3) |
""a"a""" (2-1-3) |
"""a""""a" (3-4-1) |
"""a"""a" (3-3-1) |
"""""aaa""""""""" (5-9) |
"""""aaa"""""""" (5-8) |
"""""""""""" (12) |
""""""aaa""""""""" (6-8) |
"a""a""a""a" (1-2-2-2-1) |
"""" (4) |
"a""" (1-3) |
a |
"" (2) |
"""a" (3-1) |
"""""" (6) |
""""""" (7) |
"""""""" (8) |
a"""""" (6) |
eval
or exec
or ast.literal_eval
would be valid answers, though I hope to see more creative python answers as well.
"a""""a"""
. \$\endgroup\$"a""""""" (1-7) (truthy)
is indeed already covered by"""""aaa"""""""""
(5-9). It's a test case where we have an open single-quote when the prefix isa"""""""
(so single closing quote + open&closing triple quotes). (I've deleted my comment above.) \$\endgroup\$b""
is a valid string. Maybe you should simplify to "one representinga
" \$\endgroup\$