찾다

 >  Q&A  >  본문

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个。

官方文档

PHPzPHPz2902일 전475

모든 응답(2)나는 대답할 것이다

  • 迷茫

    迷茫2017-04-18 09:19:31

    还是文档검색 및 바꾸기:

    또 다른 일반적인 작업은 패턴과 일치하는 항목을 모두 찾아 다른 문자열로 바꾸는 것입니다. sub() 메소드는 문자열 또는 함수일 수 있는 대체 값과 처리할 문자열을 사용합니다.

    으아악

    문자열에서 가장 왼쪽의 겹치지 않는 RE 항목을 대체 대체 항목으로 대체하여 얻은 문자열을 반환합니다. 패턴을 찾지 못하면 문자열이 변경되지 않고 반환됩니다.

    선택적 인수 count는 대체될 패턴 발생의 최대 개수입니다. count는 음수가 아닌 정수여야 합니다. 기본값 0은 모든 항목을 바꾸는 것을 의미합니다.

    회신하다
    0
  • 高洛峰

    高洛峰2017-04-18 09:19:31

    (@selfboot 님의 레시피로 받아가세요)

    field_pat.sub(replacement, text)re.sub()이 아닙니다...

    파이썬2

    • sub(repl, string, count=0)

      • 컴파일된 패턴을 사용한다는 점에서 sub() 함수와 동일합니다.

    Python2-sub

    으아악

    파이썬3

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

      • 컴파일된 패턴을 사용한다는 점에서 sub() 함수와 동일합니다.

    Python3-regex.sub

    으아악

    내가 답변한 질문: Python-QA

    회신하다
    0
  • 취소회신하다