Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีจำลอง scanf() ใน Python

ตามเอกสาร Python

Python ไม่มี equivalent ของ scanf() Regex ทรงพลังกว่า แต่ verbose กว่า scanf() format strings ตารางด้านล่างแสดง mapping ระหว่าง scanf() tokens และ regex:

scanf() TokenRegular Expression
%c.
%5c.{5}
%d[-+]?\d+
%e, %E, %f, %g[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?
%i[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)
%o[-+]?[0-7]+
%s\S+
%u\d+
%x, %X[-+]?(0[xX])?[\dA-Fa-f]+

เพื่อดึง filename และตัวเลขจากสตริง:

/usr/sbin/sendmail - 0 errors, 4 warnings

scanf() format:

%s - %d errors, %d warnings

Regex equivalent:

(\S+) - (\d+) errors, (\d+) warnings