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?
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.
Use AltGr - (en dash) or AltGr ⇧ Shift - (em dash).
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.
You could use .join()
to clean it up a little bit:
d = c['date']
'-'.join([d[:4], d[4:6], d[6:]])
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With