"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script. Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8......... I tried re but without success, help is appreciated, thanks.
You could use
[(int(x) if x else 0) for x in data.split(',')]
data.split(',')
splits the string into a list. It splits on the comma character:
['8', '5', '', '1', '4', '7', '', '', '', ...]
The expression
(int(x) if x else 0)
returns int(x)
if x
is True, 0 if x
is False. Note that the empty string is False.
Regular expressions are often unnecessary in Python. Given string s
, try:
','.join(x or '0' for x in s.split(','))
I am assuming you want to fill the blanks with 0. If you want a list of integers instead of a string, try this:
[(x and int(x)) or 0 for x in s.split(',')]
s = "8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
s = re.sub('((?<=,)|^)(?=,|$)', '0', s)
print s
Prints:
8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8,6,3,9,0,2,5,4,0,0,0,0,3,2,0,0,7,4,1,1,0,4,0,6,9,0,5,0,0,0,5,0,0,1,0,6,3,0,0,6,5,0,0,0,7,4,0,1,7,6,0,0,0,8,0,5,0,0,7,1,0,3,9,0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With