Python Format String To Specific Length
Chapter:
Python
Last Updated:
24-09-2023 02:58:16 UTC
Program:
/* ............... START ............... */
-----------------------------------------------------------------------------------
#Using String Slicing:
original_string = "Hello, World!"
desired_length = 15
# Truncate or pad the string to the desired length
formatted_string = original_string[:desired_length].ljust(desired_length)
print(formatted_string)
------------------------------------------------------------------------------------
#Using String Formatting:
original_string = "Hello, World!"
desired_length = 15
# Format the string to the desired length using string formatting
formatted_string = "{:<{}}".format(original_string, desired_length)
print(formatted_string)
-------------------------------------------------------------------------------------
#Using f-Strings (Python 3.6 and newer):
original_string = "Hello, World!"
desired_length = 15
# Format the string to the desired length using an f-string
formatted_string = f"{original_string:<{desired_length}}"
print(formatted_string)
-------------------------------------------------------------------------------------
# Using the str.ljust() Method:
original_string = "Hello, World!"
desired_length = 15
# Format the string to the desired length using ljust()
formatted_string = original_string.ljust(desired_length)
print(formatted_string)
-------------------------------------------------------------------------------------
/* ............... END ............... */
Notes:
-
In second example, "<{}" is a format specifier that left-aligns the string and ensures it's a minimum of desired_length characters wide. If the original string is shorter, it will be padded with spaces on the right.
- In fourth example Python's str.ljust(width, fillchar) method can be used to left-align a string and pad it with a specified character.
- By default, str.ljust() pads with spaces. You can also specify a custom fill character if needed.
- Choose the method that best fits your needs and coding style. These techniques allow you to format strings to a specific length by either truncating or padding them as necessary.