How to Split Strings into Words and Digits in Python?

Estimated read time 1 min read

You can split a string into words and digits in Python using regular expressions and the re module.

Here is an example of how to split a string into words and digits:

import re

string = "hello 123 world"
words_digits = re.findall(r'\b\w+\b|\d+', string)



['hello', '123', 'world']

In this example, the re.findall() method takes two arguments: a regular expression pattern and the string to search. The pattern \b\w+\b|\d+ matches either a word boundary followed by one or more word characters (\b\w+\b), or one or more digits (\d+).

The re.findall() method returns a list of all non-overlapping matches of the pattern in the string. In this case, it returns a list of words and digits in the order they appear in the string.

You can modify the regular expression pattern to suit your needs. For example, if you only want to split the string into words (excluding digits), you can use the pattern \b\w+\b instead.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply