Skip to content

Instantly share code, notes, and snippets.

@paddy74
Created April 12, 2023 15:27
Show Gist options
  • Save paddy74/5a5140ddedafcd2576a11824b74fcdef to your computer and use it in GitHub Desktop.
Save paddy74/5a5140ddedafcd2576a11824b74fcdef to your computer and use it in GitHub Desktop.
Helper functions for Python strings
def str_isnullorwhitespace(value: str) -> bool:
"""
Indicates whether a specified string is `null`, empty, or consists only of
white-space characters
Parameters
-----------
value: str
The string to test.
Returns
-----------
boolean
`true` if the `value` parameter is `null` or Empty, or if `value`
consists exclusively of white-space characters.
"""
return not (value and not value.isspace())
def parse_str_to_list(s: str) -> list[str]:
"""
Accepts strings formatted as lists with square brackets. Elements can be either quoted or unquoted strings, or just plain strings separated by commas or spaces.
Parameters
-----------
s: A list of strings formatted as a string.
Returns
-----------
list[str]
A list of strings.
"""
if not isinstance(s, str):
return []
# Regular expression to match quoted or unquoted strings
pattern = r'"[^"]*"|\'[^\']*\'|\w+'
# Find all matches of the pattern in the input string
matches = re.findall(pattern, nodes)
# Remove quotes from the matched strings and join them using commas
parsed_s = [x.strip("\"'") for x in matches]
return parsed_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment