Python scanf

1.6.0 · active · verified Fri Apr 17

The `scanf` library provides a pure-Python implementation of the C-style `scanf` function for parsing strings based on format specifiers. It allows users to extract data of various types from input strings, similar to its C counterpart. The current version is 1.6.0. It has a relatively low release cadence but remains actively maintained with recent commits.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `scanf.scanf()` to parse strings. It shows basic type extraction and a more complex scenario using C-style format specifiers, including `%[^,]` to read until a delimiter. It also illustrates checking for `None` as `scanf.scanf` returns `None` on no match.

import scanf

# Example 1: Basic string and integer parsing
name, age = scanf.scanf("Name: %s Age: %d", "Name: Alice Age: 30")
print(f"Parsed - Name: {name}, Age: {age}")

# Example 2: Parsing a more complex string with mixed types
# %[^,] is a scanf-specific specifier meaning 'read until a comma'
input_data = "Product: Laptop, Price: 1200.50, Quantity: 2, ID: xyz123"
format_str = "Product: %[^,], Price: %f, Quantity: %d, ID: %s"

# scanf.scanf returns a tuple of parsed values or None if no match.
result = scanf.scanf(format_str, input_data)

if result:
    product, price, quantity, product_id = result
    print(f"\nParsed data from complex string:")
    print(f"  Product: {product}")
    print(f"  Price: {price:.2f}")
    print(f"  Quantity: {quantity}")
    print(f"  ID: {product_id}")
else:
    print("\nFailed to parse the input string. Check format string and input data.")

view raw JSON →