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.

PythonForm Validation

Code

pythonsnippet
17 lines
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 -> 200

findall 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

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`.