String to words

Python, String, Regexp · Nov 2, 2020

Converts a given string into a list of words.

  • Use re.findall() with the supplied pattern to find all matching substrings.
  • Omit the second argument to use the default regexp, which matches alphanumeric and hyphens.
import re

def words(s, pattern = '[a-zA-Z-]+'):
  return re.findall(pattern, s)
words('I love Python!!') # ['I', 'love', 'Python']
words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee']
words('build -q --out one-item', r'\b[a-zA-Z-]+\b')
# ['build', 'q', 'out', 'one-item']

More like this

  • String to slug

    Converts a string to a URL-friendly slug.

    Python, String · Oct 25, 2020

  • Hex to RGB

    Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components.

    Python, String · Sep 15, 2020

  • Camelcase string

    Converts a string to camelcase.

    Python, String · Nov 2, 2020