Files
30-seconds-of-code/snippets/words.md
Isabelle Viktoria Maciohsek ac6acd66e9 Add words
2020-10-04 00:35:00 +03:00

593 B

title, tags
title tags
words 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.
import re

def words(str, pattern = '[^a-zA-Z-]+'):
  return list(filter(None, re.split(pattern, str)))
words('I love Python!!') # ['I', 'love', 'Python']
words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee']