If I have a string = "hello world sample text"
I want to be able to convert it to a list = ["hello", "world", "sample", "text"]
How can I do that with regular expressions? (other methods not using re are acceptable)
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
split() works. The re. split() function splits the given string according to the occurrence of a particular character or pattern. Upon finding the pattern, this function returns the remaining characters from the string in a list.
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .
"hello world sample text".split()
will split on any whitespace. If you only want to split on spaces
"hello world sample text".split(" ")
regex version would be something like this
re.split(" +", "hello world sample text")
which works if you have multiple spaces between the words
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With