In Python3 many methods are returning iterator or generator objects (instead of lists or other heavy objects in python2).
However, I've found that splitting string still returns list
instead of generator
or iteator
:
~$ python3
Python 3.2.2
(...)
>>> type('a b c d'.split())
<class 'list'>
Is there buildin for splitting string using generator
or iterator
?
(I know we can split it by ourself and write nice generator function. I am curious if there is something in standard library or language to do this)
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.
Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.
Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.
To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.
Check out re.finditer
from the re module => Python Docs
In brief:
""" Returns an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match. """
I think it will do what you need. For example:
import re
text = "This is some nice text"
iter_matches = re.finditer(r'\w+', text)
for match in iter_matches:
print(match.group(0))
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