Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a more efficient to replace the elements in a string based on their position?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading