将字符串中的char替换为另一个char

时间:2017-12-07 02:55:06

标签: python date format

我想使用list2中的日期格式列出1

list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']

list2 = ['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']

只需用空格

替换单个数字月份的零

2 个答案:

答案 0 :(得分:1)

试试这个:

>>> import re
>>> list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']
>>> [re.sub(r'(\d{4} )0',r'\1 ',x) for x in list1]
['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']

答案 1 :(得分:0)

另一种解决方案如下:

list1 = ['1628 04 19 21:10:32', '1752 06 15 20:05:36', '1775 04 18 09:15:56', '1865 04 14 14:54:36', '1876 05 10 15:36:27', '1879 10 22 03:45:15', '2010 09 29 04:46:28']
list2 = []

for each_item in list1:
    if each_item[5] == '0':
        each_item = each_item[0:5] + ' ' + each_item[6:]
    list2.append(each_item)

print list2

<强>输出:

['1628  4 19 21:10:32', '1752  6 15 20:05:36', '1775  4 18 09:15:56', '1865  4 14 14:54:36', '1876  5 10 15:36:27', '1879 10 22 03:45:15', '2010  9 29 04:46:28']