Adding Adjacent Numbers in a Python String

Question:

I am attempting to code a FEN number calculator based on a board:

boardPeices = ['br', 'bn', 'bb', 'bq', 'bk', 'bb', 'bn', 'br',
                'bp', 'bp', 'bp', 'bp', 'bp','bp', 'bp', 'bp',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                ' ', ' ', ' ', ' ', ' ',' ', ' ', ' ',
                'wp', 'wp', 'wp', 'wp', 'wp','wp', 'wp', 'wp',
                'wr', 'wn', 'wb', 'wq', 'wk','wb', 'wn', 'wr',
            ]

and have gotten pretty far, to where I have 8 stings, each with a row of the FEN number. Currently, the below code prints this: rnbqkbnr/pppppppp/11111111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR

print(f'{fenRow1}/{fenRow2}/{fenRow3}/{fenRow4}/{fenRow5}/{fenRow6}/{fenRow7}/{fenRow8}')

The problem is, the FEN number’s ones should be concentrated into 8’s, as there are 8 numbers next to each other. Due to everything being in strings, I cannot figure out how to add the 8 numbers together, in a way that a different position would still work, where the numbers are separated (ie, after e4)

Asked By: Owen Griffin

||

Answers:

You can use itertools.groupby:

from itertools import groupby

s = 'rnbqkbnr/pppppppp/11111111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR'

out = ''.join([x for k, g in groupby(s, lambda x: x=='1')
               for x in ([str(len(list(g)))] if k else list(g))])

Output:

'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'

Example on another input (s = 'rnbqkbnr/ppp1pppp/111p1111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR'):

'rnbqkbnr/ppp1pppp/3p4/8/8/8/PPPPPPPP/RNBQKBNR'
Answered By: mozway

Use short regex substitution:

import re

s = 'rnbqkbnr/pppppppp/11111111/11111111/11111111/11111111/PPPPPPPP/RNBQKBNR'
new_s = re.sub(r'd{2,}', lambda m: str(len(m.group())), s)

rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
Answered By: RomanPerekhrest
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.