Home > other >  Function Returns Individual Characters Rather than Strings
Function Returns Individual Characters Rather than Strings

Time:05-13

My function returns individual characters instead of words.

#!/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()))

Output of print(var_lines) in get_template_vars_test():

@HOSTNAME@

Output of print(list(get_template_vars_test())):

['\n', '@', 'H', 'O', 'S', 'T', 'N', 'A', 'M', 'E', '@', '\n']


I'm at a loss for how to return this as a word and I could use some help. Thanks for looking.


EDIT:

My original question is solved, but raises a followup question about for loops on the return and generating concatenated lists of words.

#!/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())

Output of print(get_template_vars_test()):

@HOSTNAME@

@RADIUS@

Looping over the output is broken though.

for line in get_template_vars_test():
    print(line)

Output:

@
H
O
S
T
N
A
M
E
@


@
R
A
D
I
U
S
@

Final Edit:

I fixed it by calling var_lines into a list.

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

I believe the regular expression generates an unbroken string, the affect of the combination of re.findall, re.DOTALL, and my condition. The default behavior of list apparently breaks up the string on \n.

CodePudding user response:

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

Pulling the regular expression into a list solves it. See edit in the original post.

  • Related