When working with strings in Python, you often need to format them to make the data more readable and presentable. Formatting helps in arranging the data in a way that looks good and is easy to understand.
Basic Formatting Using format()
The format() method in Python allows you to insert variables into a string in specific places, which makes it easy to create well-formatted strings.
Example of Basic Formatting
Here's an example:
|
Output will be:
You entered "Monty" "123456" |
In this example:
- The format() method is called on the string 'You entered "{}" "{}"'.
- The curly braces {} act as placeholders for the variables username and password.
- The format() method fills these placeholders with the values of username and password.
Formatting Details
Field Width and Alignment: You can specify how wide the space for each variable should be and how the content should be aligned.
|
This will print username and password each in a field of 10 characters wide.
Monty 123456 |
Right-Justification: You can also align the text to the right within the specified width.
|
This will right-align the username and password.
Monty 123456 |
Example 1: Change Counter
The following program reads the number of each type of coin from the user and calculates the total amount. It uses string formatting to present the total value in a user-friendly way.
# Function defined to do the work def main(): print("Change Counter\n") print("Please enter the count of each coin type.") quarters = eval(input("Quarters: ")) dimes = eval(input("Dimes: ")) nickels = eval(input("Nickels: ")) pennies = eval(input("Pennies: ")) total = quarters * 25 + dimes * 10 + nickels * 5 + pennies # Each {} contains an index number and symbols control appearance. # Total is divided by 100 with integer division for the first parameter (dollars) and modulus with 100 for the second parameter (cents) # See https://docs.python.org/3.6/library/stdtypes.html#str.format print("The total value of your change is ${0}.{1:02}".format(total // 100, total % 100)) main() |
The Output of Running the Program
Change Counter |
Example 2: Encoding
This example demonstrates encoding, where each character in a string is converted to its numeric representation using Unicode. The script then prints both the numeric representation and the original character.
# Sequences: encoding # A string message to encode. mymessage = 'Monty' # Try out indexing and concatenation print(mymessage[0] + mymessage[1] + mymessage[2]) # Encode: in this case we can encode and decode a character from a string. for char in mymessage: print('Numeric version:', ord(char)) print('Recover the original:', chr(ord(char))) |
Explanation:
- String Message: mymessage is the string to be encoded.
- Indexing and Concatenation: Demonstrates how to access and combine characters from the string.
- Encoding: Uses ord() to convert each character to its numeric (Unicode) representation.
- Decoding: Uses chr() to convert the numeric representation back to the original character.