I am working on splicing unwanted sections in a given list, and I'd like to do it recursively. I'm struggling to figure out the right way to delete something based off a set of tokens. For example, if I have ['a','b','c','d','e'], I'm trying to recursively remove from 'b' to 'd', which would result in ['a','e'].
Here is what has gotten me the closest thus far.
lines = """
variable "ops_manager_private" {
default = false
description = ""
}
variable "optional_ops_manager" {
default = false
}
/******
* RDS *
*******/
variable "rds_db_username" {
default = ""
}
variable "rds_instance_class" {
default = ""
}
variable "rds_instance_count" {
type = "string"
default = 0
}
"""
def _remove_set(target: list, start: str, stop: str, delete=False):
if not target:
return []
elif target[0] == start:
return target[0] + _remove_set(target[1:], start, stop, delete=True)
elif delete is True:
return _remove_set(target[1:], start, stop, delete=True)
elif target[0] == stop:
return target[0] + _remove_set(target[1:], start, stop, delete=False)
else:
return target[0] + _remove_set(target[1:], start, stop, delete=False)
if __name__ == __main__:
results = _remove_set(lines.splitlines(), 'ops_', '}\n')
Then I get this error:
Traceback (most recent call last):
# large recursive traceback
TypeError: can only concatenate str (not "list") to str
What is the right way to recursively slice a list?
target[0]with[target[0]]to fix your error.