python输入,格式化输入,以及scanf的替代方案

这篇博客探讨了Python中替代scanf的多种方法,包括普通数据读入、调用C标准库以及使用正则表达式进行格式化输入。详细讲解了不同类型的输入示例,如字符串、字符、浮点数、整数(包括八进制和十六进制)等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,普通读入数据

有一下5种方式:

n, m = [int(i) for i in temp.split(' ')]
n, m = map(int,raw_input().split(' '))
 
import sys
for line in sys.stdin:
      for data in line.split(' '):
            print data
 
import sys
arr = []
for line in sys.stdin:
      arr.append([int(i) for i in line.split(' ')])
 
import sys
arr = []
for line in sys.stdin:
      arr.append( set( line.lower.split(' ') ) )
 

while True:
    try:
        (x, y) = (int(x) for x in raw_input().split())
        print x + y
    except EOFError:
        break


二,调用c标准库

# Windows下:
from ctypes import *
msvcrt = cdll.msvcrt
msg = "Hello world!\n"
msvcrt.printf("Testing: %s", msg)

# Linux下:
from ctypes import *
libc = CDLL("libc.so.6")
msg = "Hello, world!\n"
libc.printf("Testing: %s", msg)

三,正则表达式实现scanf

在Python里,没有与scanf()直接等同的功能函数,因此需要格式化输入,就需要使用正则表达式的功能来实现,并且正则表达式的功能比scanf()更加灵活,功能更加强大,下面就来列出一些等同的表达:



scanf()格式字符串

正则表达式

%c

.

\

.{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
对于上面格式的字符串,如果使用C函数scanf()来输入,需要使用下面的格式来实现:
%s - %d errors, %d warnings
如果我们使用正则表达式来表示,如下:
(/S+) - (/d+) errors, (/d+) warnings
例子:
print('scanf()')
pattern = re.compile(r"(\S+) - (\d+) errors, (\d+) warnings")
match = pattern.match('/usr/sbin/sendmail - 0 errors, 4 warnings')
if match:
    print(match.groups())

结果输出如下:
scanf()
('/usr/sbin/sendmail', '0', '4')

%c的例子:

print('scanf() %c')
pattern = re.compile(r".")
match = pattern.match('this is for test/n')
if match:
    print(match.group())
结果输出如下:
scanf() %c
t

\的例子:

print('scanf() \')
pattern = re.compile(r".{5}")
match = pattern.match('this is for test/n')
if match:
    print(match.group())
结果输出如下:
scanf() \
this 

%e, %E, %f, %g的例子:

print('scanf() %e, %E, %f, %g')
pattern = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?")
match = pattern.match('+200.3721/n')
if match:
    print(match.group())

match = pattern.match('x9876/n')
if match:
    print(match.group())#不匹配没有输出
结果输出如下:
scanf() %e, %E, %f, %g
+200.3721

%i的例子:

print('scanf() %i')
pattern = re.compile(r"[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)")
match = pattern.match('0xAA55/n')
if match:
    print(match.group())

match = pattern.match('234.56/n')
if match:
    print(match.group())
结果输出如下:
scanf() %i
0xAA55
234

八进制的%o的例子:

print('scanf() %o')
pattern = re.compile(r"[-+]?[0-7]+")
match = pattern.match('0756/n')
if match:
    print(match.group())
match = pattern.match('898/n')

if match:
    print(match.group())#不匹配没有输出
结果输出如下:
scanf() %o
0756

字符串%s的例子:

print('scanf() %s')
pattern = re.compile(r"\S+")
match = pattern.match('深圳是一个小渔村/n')
if match:
    print(match.group())
match = pattern.match('898/n')

if match:
    print(match.group())
结果输出如下:
scanf() %s
深圳是一个小渔村
898

%u的例子:

print('scanf() %u')
pattern = re.compile(r"\d+")
match = pattern.match('756/n')
if match:
    print(match.group())

match = pattern.match('-898/n')
if match:
    print(match.group())#不匹配没有输出
结果输出如下:
scanf() %u
756

十六进制%x, %X的例子:

print('scanf() %x %X')
pattern = re.compile(r"[-+]?(0[xX])[\dA-Fa-f]+")
match = pattern.match('0x756/n')
if match:
    print(match.group())

match = pattern.match('-898/n')
if match:
    print(match.group())#不匹配没有输出
结果输出如下:
scanf() %x %X
0x756





### Python 正则表达式的常见用法 #### 创建正则表达式对象 为了高效地重复使用同一个模式,在实际编程中通常会先编译正则表达式。这可以通过 `re.compile` 方法完成,该函数接受一个模式字符串并返回一个正则表达式对象[^2]。 ```python import re pattern = r'\d+' # 定义匹配数字的简单模式 regex = re.compile(pattern) ``` #### 查找所有匹配项 当需要找到输入字符串中的所有匹配子串时,可以调用正则表达式对象上的 `findall()` 方法来获取列表形式的结果: ```python text = "There are 123 apples and 456 oranges." matches = regex.findall(text) print(matches) # 输出 ['123', '456'] ``` #### 替换匹配的内容 对于想要修改原始文本的需求来说,`sub()` 方法允许指定一个新的字符串去替代那些符合条件的部分: ```python new_text = regex.sub('NUM', text) print(new_text) # 输出 There are NUM apples and NUM oranges. ``` #### 判断是否完全匹配整个字符串 如果希望验证某个字符串能否被给定模式完整无误地表示,则应该考虑使用 `fullmatch()` 方法来进行测试: ```python test_string = "789" is_full_match = bool(regex.fullmatch(test_string)) print(is_full_match) # 输出 True 或 False 取决于 test_string 是否只包含连续的数字字符 ``` #### 执行一次搜索操作 有时只需要知道是否存在至少一处满足条件的地方而不关心具体位置的话,那么就可以利用 `search()` 来实现这样的目的;此方法会在第一次遇到成功匹配之后立即停止继续寻找其他可能存在的实例,并返回相应的 Match 对象或者 None 表示失败: ```python another_test = "abc12defg" result = regex.search(another_test) if result: print(f"Found a match at position {result.start()}: '{result.group(0)}'") else: print("No matches found.") ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值