python - adding spaces inside string using regex sub -


i have string want split 2-digit pieces. tried using regex so:

import re s = "123456789" t = re.sub('..', ".. ", s) print(t) 

i expected 12 34 56 78 9 instead got '.. .. .. .. 9'. 9 not bother me, because know have number of digits, how can tell re.sub not replace actual digit dot?

using python shell 3.5.1

edit

checked 3 answers, , work, findall seems faster (and more elegant imo ;p ):

import time import re  s = "43256711233214432"  = 10000 start = time.time() while i:     -= 1     re.sub('(..)', r"\1 ", s)     end = time.time()  elapsed = end - start print("using r\"\\1 \"    : ", elapsed)  = 10000 start = time.time() while i:     re.sub('..', r"\g<0> ", s)     -= 1 end = time.time()  elapsed = end - start print("using r\"\g<0> \" : ", elapsed)  = 10000 start = time.time() while i:     ' '.join(re.findall(r'..|.', s))     -= 1 end = time.time()  elapsed = end - start print("using findall   : ", elapsed) 

using r"\1 " : 0.25461769104003906

using r"\g<0> " : 0.09374403953552246

using findall : 0.015610456466674805

2nd edit: there better way (or way...) doing without regex?

you may use re.findall also,

>>> s = "123456789" >>> ' '.join(re.findall(r'..|.', s)) '12 34 56 78 9' >>>  

r'..|.' regex matches 2 chars or single character (first preference goes .. , .)


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -