I’m writing the following function to format some text from a file object ‘item’:
def clean(item):
lines = open(str(item)).readlines()
outp = []
switch = 1
for line in lines:
line = line.strip()
if line:
line = re.sub(' +', ' ', line)
if '%' in line:
line = line.replace('%', ' per cent')
if line.startswith('Note'):
switch = 2
if line.startswith('l\t'):
line = line.split('\t')
line[0] = '<@01_bullet_point>l<@$p>'
line = '\t'.join(line)
outp.append(get_prefix(switch,1) + line)
else:
outp.append(get_prefix(switch,2) + line)
outp.append('\n')
return ''.join(outp)
I’m getting a TypeError: unsupported operand types for +: ‘NoneType’ and ‘str’
I googled around for solutions but found http://www.skymind.com/~ocrow/python_string/, whose solution 4 seemed to confirm that I was on the right track.
The other function(s) this is referencing are confirmed working so I know the problem must be in here but, having tried to find related SO questions and checked my copy of Python in a Nutshell, I can’t figure out why I’m getting the error. My best guess was something to do with variable scope but I can’t see it and, again, searching turned up nothing I could understand as the same problem. I expect I’m missing something obvious but any help would be much appreciated.
EDIT
get_prefix is:
def get_prefix(section, type):
if section == 1:
if type == 1:
prefix = '@01_bullets:'
elif type == 2:
prefix = '@04_section_sub_subhead:'
else:
prefix = '@06_body_text:'
else:
if type == 2:
prefix = '@14_notes_sub_sub_heading:'
else:
prefix = '@16_notes_text:'
return prefix
I can’t see how it might return None.
The full traceback is:
File "rep_builder.py", line 65, in <module>
`rep.write(clean(item))`
File "rep_builder.py", line 36, in clean
`outp.append(get_prefix(switch,2) + line)`
TypeError: unsupported operand types for +: 'NoneType' and 'str'
Sorry for slow updates I’m working across two unconnectable machines (long story).
Check your indentation. Are you sure
get_prefixdoesn’t look something like this? (I ask because the indentation incleanis wrong):Indented as above,
get_prefixwill returnNoneifsectionequals1.