How to replace empty string with zero in comma separated 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 do programming when I need to parse this sequence in my sudoku script. It is necessary to obtain the above sequence of 8.5.0.1.4.7.0.0.0.7.0.1.9.3.6.0.0.8 ........ tried again, but to no avail, thanks, thanks, thanks.

+4
source share
6 answers

you can use

[(int(x) if x else 0) for x in data.split(',')] 

data.split(',') splits a string into a list. It breaks into a comma:

 ['8', '5', '', '1', '4', '7', '', '', '', ...] 

Expression

 (int(x) if x else 0) 

returns int(x) if x is True, 0 if x is False. Please note: the empty string is False.

+8
source

Regular expressions are often not needed in Python. Given s try:

 ','.join(x or '0' for x in s.split(',')) 

I assume you want to fill in the blanks 0. If you need a list of integers instead of a string, try the following:

 [(x and int(x)) or 0 for x in s.split(',')] 
+4
source
 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 

Print

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

+3
source
 >>> 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=s.split(",") >>> for n,i in enumerate(s): ... if i=="" : s[n]=0 ... >>> s ['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] >>> 
0
source

Simply put, I can think of

 [int(x or 0) for x in s.split(',')] 

or

 [int('0'+x) for x in s.split(',')] 
0
source

My solution uses map , lambda and split . The final code is as follows:

 sudoku_string = "1,2,3,,4,5,,6" output_string = map(lambda x: '0' if x=='' else x, sudoku_string.split(",")) 

If you want the output to be a list (ie [1,2,3,0,4,5,0,6] ), use

 output_list = map(lambda x: 0 if x=='' else int(x), sudoku_string.split(",") 

The map and lambda commands are very useful. map accepts a function and a list (really repeated, but a different story) and applies this function to each element of this list. So

 def plus_one(x): return x+1 map(plus_one, [1,2,3,4]) 

returns [2,3,4,5] . lambda is a way to quickly define functions, so we can write plus_one as

 lambda x: x+1 

Finally, split takes a string and creates a list by β€œsplitting” the string with the argument you pass. So, "1 2 3 4".split(" ") gives [1,2,3,4] .

0
source

Source: https://habr.com/ru/post/1306470/


All Articles