Convert 3 consecutive number in a string with a symbol
Question:
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.
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,"@")
Answers:
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 @@@
You can use the re
(regex for python) standard package, to match all groups of 3 numbers and replace them through re.sub
by the desired string.
import re
input = "kJF534kdfkj23kk222"
# [0-9] is a regex to match all digits, the {3} part tells the regex
# to search for exactly three digits occurrences
output = re.sub("[0-9]{3}", "@@@", input)
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.
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,"@")
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 @@@
You can use the re
(regex for python) standard package, to match all groups of 3 numbers and replace them through re.sub
by the desired string.
import re
input = "kJF534kdfkj23kk222"
# [0-9] is a regex to match all digits, the {3} part tells the regex
# to search for exactly three digits occurrences
output = re.sub("[0-9]{3}", "@@@", input)