Split a string every nth character to the right?

I have different very large files that I would like to place in different subfolders. I already have a sequential identifier for each folder that I want to use. I want to split the identifier on the right so that at deeper levels there are 1000 folders.

An example :

id: 100243=> result_path:'./100/243'

id: 1234567890=> resulting path:'1/234/567/890'

I found Split the string every nth character? , but all solutions are from left to right, and I also did not want to import another module for one line of code.

My current (working) solution is as follows:

import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))

Output: /home/made/00/024/102/442

, . , . , .

Update:

. .join mod .

, / . / , len(s)%3 ,

'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])

!

2:

os.path.join ( ), , os.path.join :

ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))
+4
4

, , mod one-liner:

>>> s = '1234567890'
>>> '/'.join([s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'1/234/567/890'

, dot , :

s = '100243'

- or, @MosesKoledoye:

>>> '/'.join(([s[0:len(s)%3] or '.']) + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'./100/243'

, reversing string reversing a list.

+3

, , ?

str = '1234567890'
str[::-1]

:

'0987654321'

, , .

+1

regex modulo . :

import re
s = [100243, 1234567890]
final_s = ['./'+'/'.join(re.findall('.{2}.', str(i))) if len(str(i))%3 == 0 else str(i)[:len(str(i))%3]+'/'+'/'.join(re.findall('.{2}.', str(i)[len(str(i))%3:])) for i in s]

:

['./100/243', '1/234/567/890']
+1

:

>>> line = '1234567890'
>>> n = 3
>>> rev_line = line[::-1]
>>> out = [rev_line[i:i+n][::-1] for i in range(0, len(line), n)]
>>> ['890', '567', '234', '1']
>>> "/".join(reversed(out))
>>> '1/234/567/890'
+1

Source: https://habr.com/ru/post/1689262/


All Articles