如何使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP