I have a list of strings and I'm trying to insert an underscore every two numbers. This is my code:
import re
dates=['210422', '210522', '210622']
print([re.sub("\d{2}", "_", d) for d in dates])
but the output is not what I'd like:
['____', '____', '____']
my desired output is:
["21_04_22","21_05_22","21_06_22"]
CodePudding user response:
This is not job for regex, but you can use backreferences.
import re
dates=['210422', '210522', '210622']
print([re.sub(r"(\d{2})(\d{2})(\d{2})", r"\1_\2_\3", d) for d in dates])
CodePudding user response:
You could do with re.findall
,
In [38]: ["_".join(re.findall(r"\d{2}", s)) for d in dates]
Out[38]: ['21_04_22', '21_04_22', '21_04_22']
CodePudding user response:
If your data is dates, why not treat them like dates?
from datetime import datetime
dates = ['210422', '210522', '210622']
print([datetime.strptime(d, "%d%m%y").strftime("%d_%m_%y") for d in dates])
Output:
['21_04_22', '21_05_22', '21_06_22']
CodePudding user response:
dates=['210422', '210522', '210622']
[re.sub(r'(?<=^\d{2})|(?=\d{2}$)', r'_',date) for date in dates]
['21_04_22', '21_05_22', '21_06_22']
- (?<=^\d{2}) insert underscore after 2 digits from the start
- (?=\d{2}$) insert underscore before the last 2 digits.
It is easier done with the wrap though...
from textwrap import wrap
['_'.join(wrap(date,2)) for date in dates]
['21_04_22', '21_05_22', '21_06_22']
CodePudding user response:
The answers above are great, but here is a version that doesn't require Regex
dates=['210422', '210522', '210622']
print([ d[:2] '_' d[2:4] '_' d[4:] for d in dates])
output:
['21_04_22', '21_05_22', '21_06_22']