I have the following string '2022-01-03 20:04:22' and I would like to change the last two elements to ’00’ so it looks like this '2022-01-03 20:04:00'.
I have worked out the following method:
s = '2022-01-03 20:04:22'
print(s)
n = len(s) - 2
print(n)
r = '00'
print(r)
s = s[0:n] + r
print(s)
Output:
2022-01-03 20:04:22
17
00
2022-01-03 20:04:00
It gets the job done but I feel their should be a better way.
For example, I tried this first:
s = '2022-01-03 20:04:22'
s = s.replace(s[-2:], '00')
But I end up with this: 2000-01-03 20:04:00 where the ’22’ in the year is also changes to ’00’.
I understand now that the s[-2:] extracts the value from that index which is ’22’ and then it finds this value twice in the string (in the year 2022 and in the seconds part of the datetime) and replaces them with ’00’.
Thus far, I haven’t found a solution to replace the characters that are at a specific position in the string.
>Solution :
How about string slicing:
s = s[:-2] + '00'
Output:
'2022-01-03 20:04:00'