如何使用 Python 模擬 scanf() 方法?


根據 Python 文件

Python 目前沒有等效於 scanf() 的方法。一般來說,正則表示式scanf() 格式字串更強大,但更冗長。下表列出了 scanf() 格式標記和正則表示式之間的近似等效對映。

scanf() 標記正則表示式

%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]+

為了從類似

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

這樣的字串中提取檔名和數字,需要使用如下的 scanf() 格式:

%s - %d errors, %d warnings

等效的正則表示式為:

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

更新於: 2023-11-02

6 千次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.