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

Convert 3 consecutive number in a string with a symbol

I was trying to change every 3 consecutive numbers in string with "@" symbol.
I don’t mean 1.2.3 , but every 3 numbers .

input ="kJF534kdfkj23kk222"

Desired output :

output="kJF@@@kdfkj23kk@@@"

I’m a beginner in Python and I didn’t know how to do that.

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

I tried the following but I’m having trouble in my for loop.

if i.isdigit() and (i+1).isdigit() and (i+2).isdigit():
    output = input.replace(i, "@")
    output=input.replace(i+1,"@")
    output=input.replace(i+2,"@")

    

>Solution :

I would use regular expressions:

import re

s = "kJF534kdfkj23kk222"
out = re.sub(r"\d{3}","@@@", s)
print(out)

output:

"kJF@@@kdfkj23kk@@@"

This will match every sequence of 3 consecutive digits (\d match a digit, {3} indicates a sequence of 3) and replace them with @@@

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