改变变量部分的值 - Python

时间:2018-06-11 10:56:44

标签: python

我有一个变量,其时间为H:M:S格式,如下所示

 h2='00:00:01'

我想将其中的H部分更改为10,以便它变为

h2='10:00:01'

我尝试了下面的代码,但是它没有工作

h2.split(':')[0]=10
print(h2)

输出:

00:00:01

预期产出:

10:00:01

如何更改变量部分的值?

2 个答案:

答案 0 :(得分:2)

你非常接近。

尝试:

h2='00:00:01'
h2 = h2.split(":")
h2[0] = '10'
print( ":".join(h2) )

如果您可以使用日期时间模块

import datetime
h2='00:00:01'
time = datetime.datetime.strptime(h2, "%H:%M:%S")
print( time.replace(hour=10).strftime("%H:%M:%S") )

<强>输出:

10:00:01

答案 1 :(得分:0)

您的意思是如何在适当的位置编辑字符串?你不能,python string是不可变的。您需要使用新值创建一个新字符串。你正在做的是以下

h2.split(':')  # makes a new list ['00', '00', '01']
h2.split(':')[0] = 10  # mutate said lest so it now equals ['10', '00', '01']
# then you just send that list you made into the void, you never assign it to anything

相反,您需要创建一个新对象

h2 = '00:00:01'
h2_split = h2.split(':')
h2_split[0] = '10'
h3 = ':'.join(h2_split)
h2 = h3  # optionally reassign your original variable this new value
相关问题