Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string into 2-letter segments [duplicate]

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?

like image 986
max Avatar asked Sep 19 '12 09:09

max


People also ask

Can a string be split on multiple characters?

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.

How do I split a string into a list of words?

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.


1 Answers

>>> [s[i:i + 2] for i in range(0, len(s), 2)]
['AB', 'CD', 'XY']
like image 194
Emmanuel Avatar answered Nov 08 '22 15:11

Emmanuel