Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string every nth character?

Is it possible to split a string every nth character?

For example, suppose I have a string containing the following:

'1234567890' 

How can I get it to look like this:

['12','34','56','78','90'] 
like image 657
Brandon L Burnett Avatar asked Feb 28 '12 01:02

Brandon L Burnett


People also ask

How do you split a string at every nth character?

To split a string every nth character:Use a list comprehension to iterate over a range with step N. On each iteration, use string slicing to select a slice of the string. The list will contain string slices with maximum length of N.

How can I split a string into segments of N characters in Java?

Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.

How do you split a string into an N in Python?

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 newline character in Python, pass the newline character "\n" as a delimiter to the split() function.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


2 Answers

>>> line = '1234567890' >>> n = 2 >>> [line[i:i+n] for i in range(0, len(line), n)] ['12', '34', '56', '78', '90'] 
like image 121
satomacoto Avatar answered Sep 28 '22 03:09

satomacoto


Just to be complete, you can do this with a regex:

>>> import re >>> re.findall('..','1234567890') ['12', '34', '56', '78', '90'] 

For odd number of chars you can do this:

>>> import re >>> re.findall('..?', '123456789') ['12', '34', '56', '78', '9'] 

You can also do the following, to simplify the regex for longer chunks:

>>> import re >>> re.findall('.{1,2}', '123456789') ['12', '34', '56', '78', '9'] 

And you can use re.finditer if the string is long to generate chunk by chunk.

like image 28
the wolf Avatar answered Sep 28 '22 05:09

the wolf