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.
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.
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.
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']
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.
a = a[::-1]
'123456789' - > '987654321'
a[i] = a[i:i+3]
'987654321' -> '987','654','321'
a[i] = int(a[i][::-1])
'987','654','321' -> 789, 654, 123
a = a[::-1]
789, 456, 123 -> 123, 456, 789
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]
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