findall Returns Group Tuples Not Strings
findall returns plain strings for one capture group but tuples once two or more groups appear, a shape change that trips naive parsers.
Code
import re
text = 'alice=42, bob=7, carol=100'
# 单个捕获组:findall 返回字符串列表
print('single group:', re.findall(r'\w+(?==)', text))
# 两个捕获组:findall 返回元组列表,而不是整段匹配文本
print('two groups: ', re.findall(r'(\w+)=(\d+)', text))
# 非捕获组 (?:...) 不改变返回形状,整体仍是字符串
print('non-capturing:', re.findall(r'(?:\w+)=(\d+)', text))
# 要按名字取字段时,finditer + groupdict 最可读
for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text):
info = match.groupdict()
print(info['name'], '->', int(info['score']) * 2)Output
Captured from a sandboxed run of this snippet in the build pipeline.
single group: ['alice', 'bob', 'carol']
two groups: [('alice', '42'), ('bob', '7'), ('carol', '100')]
non-capturing: ['42', '7', '100']
alice -> 84
bob -> 14
carol -> 200findall Returns Group Tuples Not Strings: what runs and why
The per-item work happens inside for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text).
Top-level bindings text hold the demo state — nothing sits inside a function scope.
What to watch for
- Package resolution never happens; all calls are built-in APIs.
Using it
Line prefixes in the output: single group:, two groups:, non-capturing:.
Key statements
for match in re.finditer(r'(?P<name>\w+)=(?P<score>\d+)', text):
info = match.groupdict()
print(info['name'], '->', int(info['score']) * 2)
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `text`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.