FEN (Forsyth-Edwards Notation) is the standard one-line text format for describing a chess position. If you work with chess data, from puzzle databases to engine analysis, you will meet it constantly. The good news is that a FEN string is simple enough that you can write a strict validator and parser in roughly 40 lines of plain Python, with no libraries.
This post walks through the format field by field, then builds the parser, then shows how to test it.
The six fields of a FEN
A complete FEN has exactly six space-separated fields. The starting position is:
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
-
Piece placement. Eight ranks from rank 8 down to rank 1, separated by
/. Uppercase letters are White pieces, lowercase are Black. A digit means that many empty squares in a row. -
Side to move.
worb. -
Castling rights. Any of
K,Q,k,q(king-side and queen-side for White and Black), or-if nobody can castle. -
En passant target square. The square a pawn skipped over on the last move (for example
e3after 1.e4), or-. - Halfmove clock. Moves since the last capture or pawn move, used for the fifty-move rule.
- Fullmove number. Starts at 1 and increases after Black moves.
Most "invalid FEN" bugs come from forgetting that a field exists, so the first check is simply len(fen.split()) == 6.
The parser
import re
def parse_fen(fen):
fields = fen.split()
if len(fields) != 6:
raise ValueError("FEN needs 6 fields, got %d" % len(fields))
placement, side, castling, ep, half, full = fields
ranks = placement.split("/")
if len(ranks) != 8:
raise ValueError("placement needs 8 ranks")
board = []
for rank in ranks:
row = []
for ch in rank:
if ch.isdigit() and ch in "12345678":
row.extend(["."] * int(ch))
elif ch in "pnbrqkPNBRQK":
row.append(ch)
else:
raise ValueError("bad character %r" % ch)
if len(row) != 8:
raise ValueError("rank %r does not have 8 squares" % rank)
board.append(row)
if side not in ("w", "b"):
raise ValueError("side to move must be w or b")
if not re.fullmatch(r"-|K?Q?k?q?", castling) or castling == "":
raise ValueError("bad castling field")
if not re.fullmatch(r"-|[a-h][36]", ep):
raise ValueError("bad en passant square")
if not half.isdigit() or not full.isdigit() or int(full) < 1:
raise ValueError("bad move counters")
flat = "".join(ranks)
if flat.count("K") != 1 or flat.count("k") != 1:
raise ValueError("each side needs exactly one king")
return {"board": board, "turn": side, "castling": castling,
"en_passant": ep, "halfmove": int(half), "fullmove": int(full)}
A few design choices worth noting:
-
Expanding digits into dots gives every rank exactly eight entries, so the length check catches both too-long and too-short ranks (for example
9orppppppppp). -
The castling regex
K?Q?k?q?enforces the canonical order KQkq, and rejects the empty string. - The en passant regex only allows ranks 3 and 6, because those are the only legal target squares.
- The king count is a cheap sanity check. It does not prove the position is reachable in a real game, only that it is structurally sensible.
Printing the board
def show(board):
return "\n".join(" ".join(r) for r in board)
pos = parse_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
print(show(pos["board"]))
print(pos["turn"], pos["castling"], pos["fullmove"])
Output:
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
w KQkq 1
Testing the failures
A validator is only useful if it rejects bad input, so test the negative cases:
for bad in [
"8/8/8/8/8/8/8/8 w - - 0 1", # no kings
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP w KQkq - 0 1", # 7 ranks
]:
try:
parse_fen(bad)
except ValueError as e:
print("rejected:", e)
You should see each side needs exactly one king and placement needs 8 ranks. In a real project, put these in pytest parametrised tests, and add cases for a rank like ppppppppp (nine squares), a missing field, and a castling field such as QK.
What this parser does not check
This is structural validation only. It does not verify that:
- the side not to move is not in check,
- pawns are not on the first or last rank,
- castling rights match the actual king and rook squares,
- the en passant square is consistent with a pawn that could have just moved.
For full legality checking, use a mature library such as python-chess, which also reads and writes PGN. The home-made version above is ideal for scripts, data cleaning and teaching.
Seeing the position
Once you have parsed a position, it helps to look at it on a board. As an example, after 1.e4 the FEN is rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1, and you can see the opening position on the board in the free ChessMoveCalc tool, which I built. It accepts a ?fen= parameter in the URL, so you can generate links from your own scripts.
Note that some tools write the en passant square (e3) after every double pawn push, while others only write it when a capture is actually possible. The strict parser above accepts both, which is what you want when reading data from different sources.
Real positions to test with
Run the parser against positions you can verify by eye. Each of these passes parse_fen:
| Position | FEN |
|---|---|
| After 1.e4 c5 (Sicilian) | rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2 |
| After 1.e4 e5 2.Nf3 | rnbqkbnr/pppp1ppp/8/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R b KQkq - 1 2 |
| King and pawn endgame | 8/8/8/4k3/8/4K3/4P3/8 w - - 0 1 |
| Fool's mate (1.f3 e5 2.g4 Qh4#) | rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3 |
A few things to notice. In the Sicilian line the en passant field is c6 because Black has just pushed the c-pawn two squares, while in the Nf3 line it is - and the halfmove clock is 1, because a knight move is neither a capture nor a pawn move. The endgame has - for castling since both kings have no rooks left. In the fool's mate position the fullmove number is 3 and White is to move, but White has no legal move: the FEN does not record checkmate, which is why a parser alone can never tell you the game is over.
Turning it into tests
Put those four positions into a small pytest file and add the failure cases you care about:
import pytest
from fen import parse_fen
GOOD = [
"rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR w KQkq c6 0 2",
"8/8/8/4k3/8/4K3/4P3/8 w - - 0 1",
]
BAD = [
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -", # 4 fields
"rnbqkbnr/ppppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", # 9 pawns
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR x KQkq - 0 1", # bad side
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w QK - 0 1", # bad order
]
@pytest.mark.parametrize("fen", GOOD)
def test_good(fen):
assert parse_fen(fen)["turn"] in "wb"
@pytest.mark.parametrize("fen", BAD)
def test_bad(fen):
with pytest.raises(ValueError):
parse_fen(fen)
Common mistakes
- Assuming ranks run a to h. In FEN the placement runs from rank 8 to rank 1, and each rank from file a to file h. Reversing either flips the board.
-
Treating the clock fields as optional. Some tools drop the last two fields. Decide whether to reject them or default to
0 1, and document it. -
Trusting castling rights blindly.
KQkqon a position with no rook on h1 is syntactically valid but illegal. Cross-check against the board if you need that guarantee. - Parsing with regular expressions only. The digit-expansion approach above catches ranks that look fine but count to nine squares.
FAQ
Can I get a FEN from a game in progress? Yes. Most analysis boards export the current position. Use it to study finished games or puzzles, not to get help during a live game.
Is FEN the same as PGN? No. PGN records a whole game as a list of moves, while FEN is a single snapshot. A PGN can start from a FEN through its [FEN "..."] header.
How do I produce a FEN from my board? Walk the ranks from 8 to 1, count runs of empty squares into digits, then append side to move, castling, en passant, and the two counters.
Takeaway
FEN looks cryptic but is six small fields with simple rules. A strict parser of about 40 lines, a handful of real positions and a few negative tests give you a dependable foundation for any chess script.
Top comments (0)