Reading Time: 1 minutes
Center a String in the Terminal in Python: Python script to center a string in the terminal.
Center a String in the Terminal in Python
# CENTER A STRING IN THE TERMINAL # Write a function that takes a string as its first parameter,and the width of the terminal in characters(80) as its second parameter. The function should return a new string that consists of the original string padded by enough spaces on its left so that the original string will appear centered within the provided width when it is printed. Call your function via a main function. # Input: Different strings and value of width of terminal in characters(80 by convention) # Sample Strings to be centered: # *** The Dark Knight *** # Christian Bale as # The Batman # Directed by: # Christopher Nolan # Output: Centered strings # Also, ensure that your file when imported into another file doesn't trigger your program automatically # THOUGHT PROCESS: Two functions: one, that returns the string by padding it on the left with ( width of terminal - length of string ) // 2 spaces; second, the main function, that calls the function with various strings. def center(string, width): if width < len(string): return string numberOfSpaces = (width - len(string)) // 2 # floored division to obtain an int to avoid: resultantString = " " * numberOfSpaces + string # TypeError: can't multiply sequence by non-int of type 'float' return resultantString def mainProgram(): widthOfOutputScreen = 80 print(center("*** The Dark Knight ***", widthOfOutputScreen)) print("\n") print(center("Christian Bale as", widthOfOutputScreen)) print(center("The Batman", widthOfOutputScreen)) print("\n") print(center("Directed by: ", widthOfOutputScreen)) print(center("Christopher Nolan", widthOfOutputScreen)) # If the file has been executed directly AND not been imported, call the main function if __name__ == "__main__": mainProgram()
Try it here. You will have to call mainProgram() function yourself, since we have made the script independent by adding the if construct.