Bootstrap FreeKB - Python (Scripting) - Printing stdout to the console
Python (Scripting) - Printing stdout to the console

Updated:   |  Python (Scripting) articles

The print command can be used to print text to the console in Python. In this example, the text Hello World is printed to the console. In Python version 3, the print statement must include parenthesis, so it's a good idea to always include parenthesis, even if you are running Python version 2, so that your scripts will continue to work on Python version 3.

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

 

Or, if the foo variable contains a value of bar, this will print bar to the console.

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

 

To print both a string and a variable, the + character can be used. 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"
print (foo + " World")

 

Or, a comma can be used. A comma will append whitespace before/after the comma thus there would be no need to include whitespace following the comma.

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

 

Here is how you can print both an integer and a variable.

#!/usr/bin/python
int = 1
print(str(int) + " World")

 

Here is how you can print both a boolean and a variable.

#!/usr/bin/python
bool = True
print(str(bool) + " World")

 

Here is how you can print two (or more) variables.

#!/usr/bin/python
base_directory   = "/usr/local"
target_directory = "/files"

print(base_directory + target_directory)

 

But better yet, just use Python3 f format curly braces.

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

 

Let's say you do something like this.

#!/usr/bin/python
used      = "193498934"
available = "340343432401"

print("Used Available")
print(used available)

 

Which returns this, where line 1 does not align with line 2.

Used Available
193498934 340343432401

 

This can be resolved by using format to set the width of each field.

print("{:<15} {:<15}".format("Used Available"))
print("{:<15} {:<15}".format(used, available))

 

Which should now return something like this.

Used           Available
193498934      340343432401

 




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 ca42f8 in the box below so that we can be sure you are a human.