在python字符串中插入这些破折号的最快方法? [英] Fastest way to insert these dashes in python string?

查看:62
本文介绍了在python字符串中插入这些破折号的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道 Python 字符串是不可变的,但我有一个字符串:

So I know Python strings are immutable, but I have a string:

c['date'] = "20110104"

我想转换成什么

c['date'] = "2011-01-04"

我的代码:

c['date'] = c['date'][0:4] + "-" + c['date'][4:6] + "-" + c['date'][6:]

看起来有点复杂,不是吗?最好将它保存为一个单独的变量,然后再做同样的事情吗?还是基本没有区别?

Seems a bit convoluted, no? Would it be best to save it as a separate variable and then do the same? Or would there basically be no difference?

推荐答案

你可以使用 .join() 来清理一下:

You could use .join() to clean it up a little bit:

d = c['date']
'-'.join([d[:4], d[4:6], d[6:]])

这篇关于在python字符串中插入这些破折号的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆