【问题标题】:Can Anybody tell why the result is different between the following 2 codes? [duplicate]谁能告诉为什么以下两个代码之间的结果不同? [复制]
【发布时间】:2018-04-15 14:35:57
【问题描述】:
import re
def find_words(num,string):
    a = re.findall('\w{int(num),}',string)
    return(a)
find_words(4, "dog, cat, baby, balloon, me")

输出为 []

#####
import re
string = "dog, cat, baby, balloon, me"
a = re.findall('\w{4,}',string)
print(a)

输出为 ['baby', 'balloon']

【问题讨论】:

  • int(num) 在字符串文字中不是4。字符串文字内容不会作为 Python 代码执行。
  • 如果你在问题中显示输出。

标签: python regex


【解决方案1】:

应该用输入变量num 替换的函数部分不会像发布的那样工作,因为它只是一个字符串。您必须先替换字符串的那一部分,如下所示:

import re

def find_words(num, string):
    target = '\w{%d,}' % num  # if num = 4, target becomes '\w{4,}'
    return re.findall(target, string)

print find_words(4, "dog, cat, baby, balloon, me")  # prints ['baby', 'balloon']

或者,您可以这样做以获得相同的结果:

target = '\w{{{},}}'.format(num)

使用format() 时需要双括号,以便在字符串中包含文字括号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多