How do I change the sequence of string? For e.g.
mys='4002-10-21'
Expected result:
'4002-21-10'
What I have tried:
I can enumerate the splitted string and then re-arrange the sequence like 1-3-2
newlist=list()
for i, v in enumerate(mys.split('-')):
newlist.append(v)
With operator.itemgetter
you can get multiple items with a single call:
>>> from operator import itemgetter
>>> '-'.join(itemgetter(0,2,1)(mys.split('-')))
'4002-21-10'
With string format you can pick values from arguments:
>>> "{0}-{2}-{1}".format(*mys.split('-'))
'4002-21-10'
With re.sub
you can capture groups and reorder them (assuming digits):
>>> import re
>>> re.sub(r'(\d+)-(\d+)-(\d+)', r'\1-\3-\2', mys)
'4002-21-10'
If you need this in pandas (as hinted in comments), you can use the regex-based approach in both DataFrame.replace
and Series.str.replace
, for example (add inplace=True
for in-place subs):
>>> import pandas as pd
>>> df = pd.DataFrame({'dates': ['4002-10-21']})
>>> df.dates.replace(r'(\d+)-(\d+)-(\d+)', r'\1-\3-\2', regex=True)
0 4002-21-10
Name: dates, dtype: object
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