Reputation: 23
Write a function that takes as parameters a character string and an integer representing the character width of the terminal. The function should return a new string consisting of the original string but with the correct amount of spaces at the beginning, so that the string is centered in a terminal window of the width that was given as a parameter when it is printed. If the number of spaces required at the beginning and at the end are different, then suppose there should be fewer spaces at the beginning.
For example: if the string is 'abc' and the terminal has 10 characters, there must be 3 spaces at the beginning and then the string must come. To complete the 10 characters there would have to be 4 trailing spaces (trailing spaces should not appear in your answer!). The len (…) function can help you calculate the length of the string that is given as a parameter.
I have received this result from the code evaluator
I would be so grateful if somebody can help me.
Upvotes: 0
Views: 379
Reputation: 23
I already do it If anyone is wondering the solution:
def centrar_texto(cadena: str, ancho_terminal: int)->str:
Cadena_int = len(cadena)
Espacios = int ((ancho_terminal /2) - (Cadena_int/2))
Texto = " " * Espacios + cadena
return (Texto)
Upvotes: 2
Reputation: 458
This code should solve your problem
import math
def center_text(text, terminal_width):
extra_space = terminal_width - len(text)
beginning_space = math.floor(extra_space / 2) # amount of space at beginning, rounding down if extra_space is odd
return(" " * beginning_space + text)
print(center_text("abc", 10))
# Output: " abc"
Upvotes: 1