If you want to print a string in the middle of a fixed width, you can calculate the number of spaces to add before and after the string to achieve center alignment. Here's an example:
def print_centered(string, width):
spaces = width - len(string)
left_spaces = spaces // 2
right_spaces = spaces - left_spaces
print(" " * left_spaces + string + " " * right_spaces)
# Example usage
text = "MyString"
width = 24
In the print_centered function, we calculate the total number of spaces required by subtracting the length of the string from the desired width. We then divide the spaces equally on both sides by using integer division (//) to obtain the number of left spaces and the number of right spaces. Finally, we concatenate the left spaces, the string, and the right spaces with the appropriate number of spaces to achieve centered alignment when printing.