Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace empty string with zero in comma-separated string?

Tags:

python

string

"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.

like image 767
Kev Avatar asked Apr 09 '10 11:04

Kev


3 Answers

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.

like image 72
unutbu Avatar answered Nov 08 '22 06:11

unutbu


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(',')]
like image 36
Dietrich Epp Avatar answered Nov 08 '22 07:11

Dietrich Epp


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

like image 32
Joachim Sauer Avatar answered Nov 08 '22 07:11

Joachim Sauer