I have a string, which I need to split into 2-letter pieces. For example, 'ABCDXY'
should become ['AB', 'CD', 'XY']
. The behavior in the case of odd number of characters may be entirely arbitrary (I'll check the length in advance).
Is there any way to do this without an ugly loop?
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 convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.
>>> [s[i:i + 2] for i in range(0, len(s), 2)]
['AB', 'CD', 'XY']
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