Lessons · Regex · the comma inside the quotes
The comma inside the quotes
A CSV field may hold a comma of its own inside quotes, so splitting a line on commas gives the wrong number of fields.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Names with commas, addresses, free-text notes. It is not an exotic case; it is Tuesday.
How to think about it
Reach for the csv module. It also handles a doubled quote meaning a literal one, and a quoted field running over several lines -- neither of which survives a split.
Worked example
len('"Smith, Ada",30'.split(','))Three pieces, where the row has two fields.'"Smith, Ada",30'.split(',')And the name has been cut in half.Your turn
Show how many pieces a naive split gives on this row.
len('"Smith, Ada",30'.split(''))Test a pattern against real text
The trap
'We control both ends and no field ever holds a comma' is a fine reason -- written down in a comment or a test, because one day one will.
Practise the comma inside the quotes on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.