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']
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.
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.
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.
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.
>>> line = '1234567890' >>> n = 2 >>> [line[i:i+n] for i in range(0, len(line), n)] ['12', '34', '56', '78', '90']
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.
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