拆分后重新格式化python字符串

时间:2016-08-27 10:57:03

标签: python

我有像“week32_Aug_24_2016”这样的字符串。 我想更改此字符串,如“week32_2016_Aug_24” 我试过这个。

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

我的预期产量是“2016年8月24日第32周”。 我已经有了,但我想知道有没有更好的方法来做到这一点。假设我有长字符串且没有拆分值是10,那么这是很长的路。所以我想知道更好的方法来安排拆分值。谢谢......

4 个答案:

答案 0 :(得分:4)

您可以使用str.split()str.join(),就像这样:

/web/dataset/call_kw/model/operation

另请注意,我已将变量string = "week32_Aug_24_2016" order = (0, 3, 1, 2) parts = string.split('_') new_string = ' '.join(parts[i] for i in order) 重命名为str,以避免影响内置str类。

答案 1 :(得分:0)

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

类似的东西。如果你想将最后一个字符串保留在中间,可以完成。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您也可以使用str.split()和format():

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