Python (Scripting) - Append to a variable

by
Jeremy Canfield |
Updated: February 11 2024
| 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