python - 为什么这里的 sub() 函数可以只传两个参数?
PHPz
PHPz 2017-04-18 09:17:31
0
2
460

一个模版系统
这是程序:

#!/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个。

官方文档

PHPz
PHPz

学习是最好的投资!

全部回复(2)
迷茫

还是文档搜索和替换:

另一个常见任务是找到某个模式的所有匹配项,并将它们替换为不同的字符串。 sub() 方法接受一个替换值,该值可以是字符串或函数,以及要处理的字符串。

雷雷

返回通过将字符串中最左边不重叠的 RE 替换为替换替换而获得的字符串。如果未找到模式,则字符串原样返回。

可选参数count是要替换的模式出现的最大次数; count 必须是非负整数。默认值 0 表示替换所有出现的情况。

小葫芦

(请搭配 @selfboot 之良方服用)

field_pat.sub(replacement, text) 并不是 re.sub()...field_pat.sub(replacement, text) 並不是 re.sub()...

Python2

  • sub(repl, string, count=0)

    • Identical to the sub() function, using the compiled pattern.

Python2-sub

>>> import re
>>> field_pat = re.compile(r'\[(.+?)\]')
>>> field_pat
<_sre.SRE_Pattern object at 0x7fa09b67fdd8>
>>> type(field_pat)
<type '_sre.SRE_Pattern'>
>>> field_pat.sub
<built-in method sub of _sre.SRE_Pattern object at 0x7fa09b67fdd8>
>>> help(field_pat.sub)
sub(...)
    sub(repl, string[, count = 0]) --> newstring
    Return the string obtained by replacing the leftmost non-overlapping
    occurrences of pattern in string by the replacement repl.

Python3

  • regex.sub(repl, string, count=0)

      Python2

    • sub(repl, string, count=0)
Identical to the sub() function, using the compiled pattern.


Python2-sub

>>> import re
>>> field_pat = re.compile(r'\[(.+?)\]')
>>> field_pat
re.compile(r'\[(.+?)\]', re.UNICODE)
>>> type(field_pat)
_sre.SRE_Pattern
>>> field_pat.sub
<function SRE_Pattern.sub>
>>> help(field_pat.sub)
sub(...) method of _sre.SRE_Pattern instance
    sub(repl, string[, count = 0]) -> newstring.
    Return the string obtained by replacing the leftmost non-overlapping
    occurrences of pattern in string by the replacement repl.

Python3

🎜🎜 🎜regex.sub(repl, string, count=0)🎜 🎜🎜🎜Identical to the sub() function, using the compiled pattern.🎜🎜🎜 🎜🎜 🎜Python3 - regex.sub🎜 rrreee 🎜 🎜🎜我回答过的问题🎜: Python-QA🎜
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板