SumanKalyan
SumanKalyan

Reputation: 1761

Re format a python string after splitting

I have string like "week32_Aug_24_2016". I want to change this string like "week32_2016_Aug_24" I have tried this.

str = "week32_Aug_24_2016"
wk = str.split('_')
newstr = wk[0]+" "+wk[3]+" "+wk[1]+" "+wk[2]

My expected output is "week32 2016 Aug 24". I already got that but I want to know is there any better way to do this. Suppose I have long string and no of split value is 10, then this is very long way. So I want to know a better way to arrange the split values. Thanks....

Upvotes: 0

Views: 69

Answers (4)

selfboot
selfboot

Reputation: 1520

You can make use str.split() and format() as well:

str = "week32_Aug_24_2016"
wk = str.split('_')
newstr = "{} {} {} {}".format(wk[0], wk[3], wk[1], wk[2])

Upvotes: 0

Sundeep
Sundeep

Reputation: 23667

>>> import re
>>> string = "week32_Aug_24_2016"
>>> re.sub(r'_(.*)_(.*)_(.*)', r' \3 \1 \2', string)
'week32 2016 Aug 24'

Upvotes: 0

ahad alam
ahad alam

Reputation: 71

str = "week32_Aug_24_2016"
wk = str.split('_')
i=0;
newstr="";
while(i<len(wk)):
    newstr=newstr+wk[i]+" "
    i=i+1
print newstr

Something like that. If you want to keep last string in the middle it can be done.

Upvotes: 0

Delgan
Delgan

Reputation: 19617

You can make use of both str.split() and str.join(), simply like this:

string = "week32_Aug_24_2016"
order = (0, 3, 1, 2)
parts = string.split('_')

new_string = ' '.join(parts[i] for i in order)

Also, note that I renamed your variable str to string to avoid shadowing built-in str class.

Upvotes: 4

Related Questions