-1

Hi Team is there a way to append string in python, I mean i need to declare the variable globally and append the strings together and write in my file without changing the variable name.

For Example

example_string = ''
def method1():
    example_string = 'Value1'
def method2():
    example_string = 'value2'
def method3():
    example_string = 'value3'
print(example_string )

Now I want my the result to be printed as 'Value1 value2 value3', This is what im looking for can anyone help me on this.

1 Answers1

0

Use global keyword to make changes to global variables in functions. Use += to append to a string.

example_string = ''

def method1():
    global example_string
    example_string += 'value1'

def method2():
    global example_string
    example_string += 'value2'

def method3():
    global example_string
    example_string += 'value3'

Note that in order to get this last string you need to call all three functions

method1()
method2()
method3()
print(example_string)
Oleg Ivanytskyi
  • 959
  • 2
  • 12
  • 28
  • Just note that 1/ global variables are evil and 2/ due to [what Python variables really are](https://nedbatchelder.com/text/names.html) and namespacing rules rebinding (by opposition with mutating) a global will not necessarily behave as expected outside the module itself. – bruno desthuilliers Apr 07 '20 at 08:34
  • Shall i go with String concatenation – Eager2Learn Apr 07 '20 at 09:02
  • @Eager2Learn well, that depends on what you are actually doing. This is the most straightforward way to do what you asked for – Oleg Ivanytskyi Apr 07 '20 at 12:29