Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into groups of 3 characters [duplicate]

I have a string

ddffjh3gs

I want to convert it into a list

["ddf", "fjh", "3gs"]

In groups of 3 characters as seen above. What is the best way to do this in python 2.7?

like image 259
Qwerty Avatar asked May 15 '17 15:05

Qwerty


People also ask

How do I split a string into multiple parts?

As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.

Can split () take multiple arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.


1 Answers

Using list comprehension with string slice:

>>> s = 'ddffjh3gs'
>>> [s[i:i+3] for i in range(0, len(s), 3)]
['ddf', 'fjh', '3gs']
like image 168
falsetru Avatar answered Oct 19 '22 16:10

falsetru