30秒学会 Python 片段 · 2022年4月20日

30秒学会 Python 片段 – String to words

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']

翻译自:https://www.30secondsofcode.org/python/s/words