从函数返回一个值? [英] Returning a value from function?
问题描述
我正在尝试编写一个函数来分析一些文本和正则表达式模式.示例:
I am trying to write a function to analyze some text and a regular expression pattern. Example:
import re
def foo(input_pattern, text):
pattern = re.compile(r'input_patern', re.I)
find = pattern.findall(text)
ans = ' '.join(i for i in find).lower()
'''some how return'''
text = input('Test: ')
'''Text could be: My name is Joe Joe Joe '''
input_pattern = input('Pattern: ')
'''Pattern could be: '(Name|Joe)' '''
foo(input_pattern, text)
'''Get ans'''
print(ans)
但是,我似乎无法从函数中获取字符串 (ans).我确实环顾四周寻找答案,但找不到工作示例.如果你能接受,你能告诉我我将如何使用连接来制作依赖于字符串的表达式.我使用的是 python 3.6.4 并且使用的是 Mac OS X.
However, I can't seem to get a string (ans) form the function. I did look around for a answer, but could not find a working example. If you feel up to it, could you tell me how I would use concatenation to make a expression that depends on a string. I am using python 3.6.4 and am using Mac OS X.
推荐答案
从函数返回一个合理的值,并将函数调用的结果赋给一个变量.请注意,函数内的 ans
变量是本地变量,因此无法在函数外部访问:
Return a sensible value from the function and assign the result of the function call to a variable. Note that the ans
variable inside your function is local and, therefore, not accessible outside of the function:
def foo(input_pattern, text):
# ...
return ' '.join(i for i in find).lower() # return!
# ...
ans = foo(input_pattern, text) # assign!
print(ans)
这篇关于从函数返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!