Using Dictionary for Named Placeholders:

You can use a dictionary to specify values for named placeholders.

Example:

data = {'name': 'Sam', 'age': 35}
print("My name is {name} and I am {age} years old.".format(**data))

Output:

My name is Sam and I am 35 years old.

The str.format() method provides great flexibility and readability for string formatting in Python, making it a versatile tool for a wide range of use cases. You can also put a formatting expression inside the curly brackets, which lets you alter the way the string is formatted. For example, the formatting expression {:.2f} means that you’d format this as a float number, with two digits after the decimal dot. The colon acts as a separator from the field name, if you had specified one. You can also specify text alignment using the greater than operator: >. For example, the expression {:>3.2f} would align the text three spaces to the right, as well as specify a float number with two decimal places.

# Inserting values
print("My name is {} and I'm {} years old.".format("John", 30))

# Named placeholders
print("My name is {name} and I'm {age} years old.".format(name="John", age=30))

# Number formatting
print("{:,}".format(1234567))  # Output: 1,234,567
print("{:.2f}".format(123.4567))  # Output: 123.46
print("{:.0%}".format(0.1234))  # Output: 12%

# Alignment and padding
print("{:<10}".format("left-aligned"))  # Output: left-aligned   
print("{:>10}".format("right-aligned"))  # Output:   right-aligned
print("{:^10}".format("centered"))  # Output:   centered  
print("{:*^10}".format("centered"))  # Output: ***centered***

# Date and time formatting
from datetime import datetime, timedelta

# Current date and time
print("{:%Y-%m-%d %H:%M:%S}".format(datetime.now()))

# Specific date and time
print("{:%Y-%m-%d %H:%M:%S}".format(datetime(2022, 12, 31, 23, 59, 59)))

# Date and time with timezone
from pytz import timezone
print("{:%Y-%m-%d %H:%M:%S %Z}".format(datetime.now(timezone('US/Eastern'))))

# Date and time with specific format
print("{:%B %d, %Y}".format(datetime.now()))  # Output: July 29, 2024

# Time duration
print("{:%H hours, %M minutes, %S seconds}".format(timedelta(hours=12, minutes=30, seconds=45)))

# Hexadecimal and binary formatting
print("{:x}".format(123))  # Output: 7b
print("{:b}".format(123))  # Output: 1111011

# Conditional formatting
print("The answer is {answer}.".format(answer="yes" if True else "no"))

# Multiline strings
print("""
{title}
{line}
{body}
""".format(title="Title", line="-" * 50, body="This is a multiline string."))

# Repeating strings
print("Hello " * 5)  # Output: Hello Hello Hello Hello Hello

# Slicing strings
print("Hello World"[0:5])  # Output: Hello

# Case conversion
print("hello world".upper())  # Output: HELLO WORLD
print("HELLO WORLD".lower())  # Output: hello world
print("hello world".title())  # Output: Hello World

# String concatenation
print("Hello " + "World")  # Output: Hello World
print(" ".join(["Hello", "World"]))  # Output: Hello World

# String formatting with dictionaries
person = {"name": "John", "age": 30}
print("My name is {name} and I'm {age} years old.".format(**person))

# String formatting with lists
numbers = [1, 2, 3]
print("The numbers are {0}, {1}, and {2}.".format(*numbers))

# String formatting with custom objects
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("John", 30)
print("My name is {name} and I'm {age} years old.".format(**person.__dict__))

Using f-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals.

name = "Bob"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
from datetime import datetime, timedelta

# Get the current year and month
current_year = datetime.now().year
current_month = datetime.now().month

# Create a list of months and years
months_years = [(current_year, month) for month in range(1, 13)]
print("List of months for the current year:")
for year, month in months_years:
    print(f"Year: {year}, Month: {month}")

# Alternatively, create a list for the next 12 months starting from the current month
months_years_dynamic = [(current_year + (current_month + i - 1) // 12, (current_month + i - 1) % 12 + 1) for i in range(12)]
print("nDynamic list of months starting from the current month:")
for year, month in months_years_dynamic:
    print(f"Year: {year}, Month: {month}")
# Generate report titles for each month of the current year
report_titles = [f"Report for {datetime(current_year, month, 1).strftime('%B %Y')}" for month in range(1, 13)]
print("nReport Titles for Each Month:")
for title in report_titles:
    print(title)

months = ["January", "February", "March", "April", "May", "June",
         "July", "August", "September", "October", "November", "December"]
years = range(2023, 2025)  # Adjust range as needed

month_year_variables = [f"{month}_{year}" for month in months for year in years]
print(month_year_variables)

# Output: ['January_2023', 'February_2023', ..., 'December_2024']

month_dict = {
    1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June",
    7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"
}

years = range(2023, 2025)

month_year_variables = [f"{month_dict[month]}_{year}" for month in years for year in range(1, 13)]
print(month_year_variables)

# Output: ['January_2023', 'February_2023', ..., 'December_2024']

Formatting Numbers

You can format numbers directly within f-strings.

number = 1234.56789
formatted_number = f"Formatted number: {number:.2f}"
print(formatted_number)

Formatting Using the % Operator

An older method but still in use, the % operator allows for simple string formatting.

name = "Charlie"
age = 22
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)

Head to Next


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Pages ( 4 of 8 ): « Previous123 4 56 ... 8Next »

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading