Bootstrap FreeKB - Python (Scripting) - Append to a variable
Python (Scripting) - Append to a variable

Updated:   |  Python (Scripting) articles

Let's say you have a variable named foo that contains a value of Hello.

#!/usr/bin/python
foo = "Hello"
print(foo)

 

The + character can be used to append to the beginning or end of the a variable. In this example, World is appended to the end of the foo variable. The + character will NOT append whitespace, which means in this scenario you would want to include a single whitespace following the + character.

#!/usr/bin/python
foo = "Hello"
foo = foo + " World"
print(foo)

 

In this example, Hello is appended to the beginning of the foo variable.

#!/usr/bin/python
foo = "World"
foo = "Hello " + foo
print(foo)

 

Or, better yet, like this.

#!/usr/bin/python
foo = "Hello"
foo += " World"
print(foo)

 

\n can be used if you want to include new lines.

#!/usr/bin/python
foo = "Hello"
foo += "\nWorld"
print(foo)

 

Or, f-string can be used.

#!/usr/bin/python3
foo = "World"
foo = f"Hello {foo}"
print(foo)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter c1ad36 in the box below so that we can be sure you are a human.