Fastest way to insert these dashes in python string?

前端 未结 8 1486
失恋的感觉
失恋的感觉 2021-02-13 16:34

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

c[\'date\'] = \"20110104\"

Which I would like to convert to

c[\'da         


        
8条回答
  •  你的背包
    2021-02-13 17:05

    s = '20110104'
    
    
    def option_1():
        return '-'.join([s[:4], s[4:6], s[6:]])
    
    def option_1a():
        return '-'.join((s[:4], s[4:6], s[6:]))
    
    def option_2():
        return '{}-{}-{}'.format(s[:4], s[4:6], s[6:])
    
    def option_3():
        return '%s-%s-%s' % (s[:4], s[4:6], s[6:])
    
    def option_original():
        return s[:4] + "-" + s[4:6] + "-" + s[6:]
    

    Running %timeit on each yields these results

    • option_1: 35.9 ns per loop
    • option_1a: 35.8 ns per loop
    • option_2: 36 ns per loop
    • option_3: 35.8 ns per loop
    • option_original: 36 ns per loop

    So... pick the most readable because the performance improvements are marginal

提交回复
热议问题