Recent Changes - Search:

Oktatás

* Programozás 2
  + feladatsor
  + C feladatsor
  + Python feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

* Adator. prog.
  + feladatsor
  + quick link

Teaching

• Prog. for Data Sci.
  ▸ exercises
  ▸ quick link

teaching assets


Félévek

* 2026/27/1
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ✦C++, ✦Clojure, ✦Scala


[ edit | logout ]
[ sandbox | passwd ]

Extract data from a formatted string

See also:

scanf()

scanf()
from parse import parse


def main():
    s = "mul(11,8)"

    p = parse("mul({a},{b})", s)

    print(p["a"])  # "11"
    print(p["b"])  # "8"
import std/strscans


let s = "mul(11,8)"

var a, b: int

if s.scanf("mul($i,$i)", a, b):
  echo a  # 11 ; as int
  echo b  # 8  ; as int


var v1, v2: string

if s.scanf("mul($+,$+)", v1, v2):
  echo v1  # "11" ; as string
  echo v2  # "8"  ; as string

This is a 3rd-party library. You can install it with pip.

  • scanf() returns true if the operation was successful; false otherwise
  • $i: integer
  • $+: string whose length is at least 1

The most important constructions (see the docs for a full list):

$i Matches a decimal integer. Uses parseInt.
$f Matches a floating-point number. Uses parseFloat.
$c Matches a single ASCII character.
$s Skips optional whitespace(s). Matches multiple whitespace characters.
$$ Matches a single dollar sign.
$* Matches until the token following the $* was found. The match is allowed to be of 0 length.
$+ Matches until the token following the $+ was found. The match must consist of at least one char.

scanTuple()

This module has another useful macro called scanTuple(). It's quite similar to C's scanf().

Let's say that we want to read a line from the standard input that contains three integers:

2 3 5

In C, we'd do this:

int a, b, c;
scanf("%d %d %d", &a, &b, &c);

In Nim:

import std/strscans

let (ok, a, b, c) = scanTuple(stdin.readLine, "$i $i $i")
if ok:
  echo a
  echo b
  echo c

It returns a tuple. The tuple starts with a bool which indicates if the scan was successful followed by the requested data. If you're 100% sure that the input is correct, you can swallow the bool value by using the dummy variable underscore ('_').

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 November 08, 12:02