Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用另一个字符替换字符串中的字符_Python_Date_Format - Fatal编程技术网

Python 用另一个字符替换字符串中的字符

Python 用另一个字符替换字符串中的字符,python,date,format,Python,Date,Format,我想使用列表2中的日期格式列出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

我想使用列表2中的日期格式列出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']
只需将单个数字月份中的零替换为空格即可

尝试以下操作:

>>> 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']

另一种解决办法如下:

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']

你赢了我!