python - 为什么这里的 sub() 函数可以只传两个参数?

查看:279
本文介绍了python - 为什么这里的 sub() 函数可以只传两个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

一个模版系统
这是程序:

#!/usr/bin/env python
# templates.py

import fileinput, re

# Match strings in [ ]
field_pat = re.compile(r'\[(.+?)\]')

# Collect variables
scope = {}

# for re.sub
def replacement(match):
    code = match.group(1)
    try:
        # If string can be evaluate out a value, return it.
        return str(eval(code, scope))
    except SyntaxError:
        # else exec the assignment statement in action scope.
        exec code in scope
        # ...... return empty string
        return ''

# Get all text in a string
# Also, there is another way, consider Chapter 11
lines = []
for line in fileinput.input():
    lines.append(line)
    text = ''.join(lines)

# replace all items match field pattern
print field_pat.sub(replacement, text)

另外这是 strings.txt 文件内的内容:

[x = 2]
[y = 3]
The sum of [x] and [y] is [x + y]

运行结果如下:

The sum of 2 and 3 is 5

我的疑问是:
程序的最后一行

print field_pat.sub(replacement, text)

为何只有两个参数?
根据官方对 re.sub() 的文档,re.sub() 的最少参数是3个。

官方文档

解决方案

还是文档Search and Replace

Another common task is to find all the matches for a pattern, and replace them with a different string. The sub() method takes a replacement value, which can be either a string or a function, and the string to be processed.

.sub(replacement, string[, count=0])

Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn’t found, string is returned unchanged.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences.

这篇关于python - 为什么这里的 sub() 函数可以只传两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆