4 回答

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以使用字符串格式將零填充到字符串,例如填充到左側(cè):
>>> nums = ['10:30', '9:30', '11:0']
>>> ['{:0>2}:{:0>2}'.format(*n.split(':')) for n in nums]
['10:30', '09:30', '11:00']
或者,將字符串轉(zhuǎn)換為數(shù)字:
>>> ['{:02d}:{:02d}'.format(*map(int, n.split(':'))) for n in nums]
['10:30', '09:30', '11:00']

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
一個(gè)解決方案傾向于這些看起來很像日期的事實(shí)可能是......
設(shè)置您的列表
nums = ["10:30", "9:30", "11:0"]
遍歷列表轉(zhuǎn)換,獲取時(shí)間并刪除(技術(shù)術(shù)語)最后 3 個(gè)字符
for item in nums:
print(str(datetime.strptime(item, '%H:%M').time())[:-3])
打印輸出
10:30
09:30
11:00

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
如果數(shù)字是單一的,我需要加零
使用列表理解
nums = ["10:30", "9:30", "11:0"]
nums_added = [ i + "0" if len(i.split(":")[1]) == 1 else i for i in nums]
print(nums_added)
輸出:
['10:30', '9:30', '11:00']

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊
這是一個(gè)利用zfill&ljust
nums = ["10:30", "9:30", "11:0"]
fixed = []
for t in nums:
x, y = t.split(':')
fixed.append(x.zfill(2) + ':' + y.ljust(2, '0'))
print(fixed)
添加回答
舉報(bào)