我的函式回傳單個字符而不是單詞。
#!/usr/bin/env python3
import re
template_variables = '''
### VARIABLE START ###
@HOSTNAME@
### VARIABLE END ###
'''
# Get variable configuration from template
def get_template_vars_test():
for var_lines in re.findall('### VARIABLE START ###(.*?)### VARIABLE END ###', template_variables, re.DOTALL): # Find content between START and END delimiters
print(var_lines)
return var_lines
# Display the function's output as a list
print(list(get_template_vars_test()))
print(var_lines)in 的輸出get_template_vars_test():
@主機名@
輸出print(list(get_template_vars_test())):
['\n', '@', 'H', 'O', 'S', 'T', 'N', 'A', 'M', 'E', '@', '\n' ]
我不知道如何將其作為一個詞回傳,我可以使用一些幫助。感謝您的關注。
編輯:
我最初的問題已解決,但提出了一個關于回傳時的 for 回圈和生成連接的單詞串列的后續問題。
#!/usr/bin/env python3
import re
template_variables = '''
### VARIABLE START ###
@HOSTNAME@
@RADIUS@
### VARIABLE END ###
'''
# Get variable configuration from template
def get_template_vars_test():
for var_lines in re.findall('### VARIABLE START ###(.*?)### VARIABLE END ###', template_variables, re.DOTALL): # Find content in template_variables between START and END delimiters
return var_lines
print(get_template_vars_test())
輸出print(get_template_vars_test()):
@主機名@
@半徑@
但是回圈輸出被破壞了。
for line in get_template_vars_test():
print(line)
輸出:
@
H
O
S
T
N
A
M
E
@
@
R
A
D
I
U
S
@
最終編輯:
var_lines我通過呼叫串列來修復它。
def get_template_vars():
with open(read_file) as template:
for var_lines in re.findall('### VARIABLE START ###(.*?)### VARIABLE END ###', template.read(), re.DOTALL):
var_list = [ var_lines ]
return var_list
我相信正則運算式會生成一個完整的字串,re.findall、re.DOTALL 和我的條件組合的影響。list 的默認行為顯然會破壞 \n 上的字串。
uj5u.com熱心網友回復:
def get_template_vars():
with open(read_file) as template:
for var_lines in re.findall('### VARIABLE START ###(.*?)### VARIABLE END ###', template.read(), re.DOTALL):
var_list = [ var_lines ]
return var_list
將正則運算式拉入串列可以解決它。請參閱原始帖子中的編輯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473214.html
標籤:Python python-3.x 功能 字典 返回
上一篇:合并兩個交換專案的字典
