Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the order of string in python

Tags:

python

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)
like image 209
shantanuo Avatar asked Nov 27 '22 05:11

shantanuo


1 Answers

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
like image 95
randomir Avatar answered Nov 29 '22 17:11

randomir