Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to insert these dashes in python string?

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

c['date'] = "20110104"

Which I would like to convert to

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

My code:

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?

like image 672
LittleBobbyTables Avatar asked Jan 17 '13 20:01

LittleBobbyTables


People also ask

What is S %% in Python?

The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string.

How do I print a dash?

Use AltGr - (en dash) or AltGr ⇧ Shift - (em dash).

How do you insert between strings in Python?

We first use the string. find() method to get the substring index in the string, after which we need to insert another string. After getting the substring index, we split the original string and then concatenate the split strings and the string we need to insert using the + operator to get the desired string.


2 Answers

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

d = c['date']
'-'.join([d[:4], d[4:6], d[6:]])
like image 98
Blender Avatar answered Oct 13 '22 01:10

Blender


Dates are first class objects in Python, with a rich interface for manipulating them. The library is datetime.

> import datetime
> datetime.datetime.strptime('20110503','%Y%m%d').date().isoformat()
'2011-05-03'

Don't reinvent the wheel!

like image 33
Colonel Panic Avatar answered Oct 13 '22 00:10

Colonel Panic