0

I want to concatenate to get a big string:

big_str = ''
def create_big_str():
    with open('big.txt', 'r') as f:
        for line in f:
            if not line:
                continue

            big_str = big_str + ' ' + line

then in other places, i want to use the 'big_str' variable. But it reports the error:

UnboundLocalError: local variable

at the line:

big_str = big_str + ' ' + line

Add the 'global' doesn't help either.

ling
  • 1,555
  • 3
  • 18
  • 24

2 Answers2

1

You need to pass big_str to the function in the declaration statement:

def create_big_str(big_str):
tshah
  • 11
  • 4
  • How is this different from the global keyword way? – ling Feb 02 '20 at 17:02
  • You would be creating a local variable inside the function (above I called it 'big_str', but you can call it 'x' or something different, which is preferred). The function should return the final string and you can then assign to another variable or 'big_str'. – tshah Feb 02 '20 at 19:36
1

In order to change a global variable from inside a function, you explicitly have to declare that you intend to do that:

big_str = ''
def create_big_str():
    global big_str  # note this line
    with open('big.txt', 'r') as f:
        for line in f:
            if not line:
                continue

            big_str = big_str + ' ' + line

Krisz
  • 1,884
  • 12
  • 17