Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right split a string into groups of 3

What is the most Pythonic way to right split into groups of threes? I've seen this answer https://stackoverflow.com/a/2801117/1461607 but I need it to be right aligned. Preferably a simple efficient one-liner without imports.

  • '123456789' = ['123','456','789']
  • '12345678' = ['12','345','678']
  • '1234567' = ['1','234','567']
like image 253
user1461607 Avatar asked Aug 08 '13 08:08

user1461607


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.

How do I split a string into string?

Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.


2 Answers

Another way, not sure about efficiency (it'd be better if they were already numbers instead of strings), but is another way of doing it in 2.7+.

for i in map(int, ['123456789', '12345678', '1234567']):
    print i, '->', format(i, ',').split(',')

#123456789 -> ['123', '456', '789']
#12345678 -> ['12', '345', '678']
#1234567 -> ['1', '234', '567']
like image 60
Jon Clements Avatar answered Sep 19 '22 12:09

Jon Clements


simple (iterated from the answer in your link):

[int(a[::-1][i:i+3][::-1]) for i in range(0, len(a), 3)][::-1]

Explanation : a[::-1] is the reverse list of a We will compose the inversion with the slicing.

Step one : reverse the list

 a           =   a[::-1]
'123456789' - > '987654321'

Step Two : Slice in parts of three's

 a[i]           =   a[i:i+3]
 '987654321'    ->  '987','654','321'

Step Three : invert the list again to present the digits in increasing order

 a[i]           =  int(a[i][::-1])
 '987','654','321' -> 789, 654, 123

Final Step : invert the whole list

 a           =   a[::-1]
 789, 456, 123 -> 123, 456, 789

Bonus : Functional synthetic sugar

It's easier to debug when you have proper names for functions

invert = lambda a: a[::-1]
slice  = lambda array, step : [ int( invert( array[i:i+step]) ) for i in range(len(array),step)  ]

answer = lambda x: invert ( slice ( invert (x) , 3 ) )
answer('123456789')
#>> [123,456,789]
like image 42
lucasg Avatar answered Sep 21 '22 12:09

lucasg