From ac6acd66e967dd42a681592ddbceff0382d467fb Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Sun, 4 Oct 2020 00:35:00 +0300 Subject: [PATCH] Add words --- snippets/words.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/words.md diff --git a/snippets/words.md b/snippets/words.md new file mode 100644 index 000000000..e9034fff8 --- /dev/null +++ b/snippets/words.md @@ -0,0 +1,22 @@ +--- +title: words +tags: string,regexp,beginnner +--- + +Converts a given string into an array of words. + +- Use `re.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. +- Use `filter()` in combination with `None` to remove any empty strings. +- Omit the second argument to use the default regexp. + +```py +import re + +def words(str, pattern = '[^a-zA-Z-]+'): + return list(filter(None, re.split(pattern, str))) +``` + +```py +words('I love Python!!') # ['I', 'love', 'Python'] +words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee'] +```