Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using regex.finditer and translate - Should be easy to understand solution in Clear category for Currency Style by Selindian
import re
def checkio(line: str) -> str:
# your code here
newline = ''
regex = re.compile(r'\$\d+(\.\d{3})*(,\d{1,2})?(?!\d)')
"""
\$ matches the character $
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
1st Capturing Group (\.\d{3})*
* matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\. matches the character .
\d matches a digit (equivalent to [0-9])
{3} matches the previous token exactly 3 times
2nd Capturing Group (,\d{1,2})?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
, matches the character ,
\d matches a digit (equivalent to [0-9])
{1,2} matches the previous token between 1 and 2 times, as many times as possible, giving back as needed (greedy)
Negative Lookahead (?!\d)
Assert that the Regex below does not match
\d matches a digit (equivalent to [0-9])
"""
lastend = 0
for match in regex.finditer(line):
newline += line[lastend:match.start()]
currency_str = line[match.start():match.end()]
mytable = currency_str.maketrans(',.', '.,')
currency_str = currency_str.translate(mytable)
newline += currency_str
lastend = match.end()
newline += line[lastend:]
return newline
if __name__ == '__main__':
print("Example:")
print(checkio('$5.34'))
# These "asserts" are used for self-checking and not for an auto-testing
assert checkio('$5.34') == '$5.34'
assert checkio('$5,34') == '$5.34'
assert checkio('$222,100,455.34') == '$222,100,455.34'
assert checkio('$222.100.455,34') == '$222,100,455.34'
assert checkio('$222,100,455') == '$222,100,455'
assert checkio('$222.100.455') == '$222,100,455'
print("Coding complete? Click 'Check' to earn cool rewards!")
March 22, 2022
Comments: