Lines in python: functions and methods of lines in python

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

The Essentials of String Formatting in Python

String formatting stands as one of the most powerful and convenient tools in the Python language. This mechanism provides flexible control over information output across various development scenarios. Whether the task is creating reports, generating log files, or developing a user interface, beautifully and correctly formatted text plays a key role in information perception.

String formatting becomes particularly crucial when working with numerical data, dates, tables, and multi-level templates. Proper text formatting significantly enhances code readability, simplifies debugging and logging processes, and improves the display of results in user interfaces.

In a professional development environment, formatted strings often become an integral part of templates, configuration files, and HTML reports. Correctly using this tool allows for the creation of more maintainable and understandable code.

Three Main Approaches to Formatting

Python offers developers three primary methods for string formatting:

  • f-strings — the modern approach, available since Python 3.6
  • The .format() method — a versatile method compatible with older versions
  • %-formatting — the classic C-style, inherited from the C language

In this article, we will delve into each of these methods in detail. Special attention will be given to f-strings as the most readable and performant way to format strings. We will also cover the formatting of various number types, including floating-point values, percentages, and exponential notation. We will explore text alignment techniques, working with templates, and practical examples from real-world development projects.

f-strings: The Modern Standard for Formatting

Basic Syntax and Capabilities

Introduced in Python 3.6, f-strings were a breakthrough in code convenience and readability. They are special string literals that start with an f prefix before the opening quotes. Inside these strings, you can embed variables and expressions within curly braces {}.

name = "Ivan"
age = 30
print(f"Hello, my name is {name}, and I am {age} years old.")

The key advantage of f-strings is the ability to use not just variables, but any valid Python expression:

print(f"In 5 years, I will be {age + 5} years old.")

You can also call functions and methods inside f-strings:

def square(x):
    return x * x

print(f"The square of 4 is: {square(4)}")

Advanced f-string Features

f-strings support accessing object attributes and collection elements:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Maria", 25)
print(f"Employee: {person.name}, Age: {person.age}")

data = {"city": "Moscow", "population": 12500000}
print(f"The city of {data['city']} has a population of {data['population']:,} people.")

Formatting Numbers with f-strings

f-strings provide powerful options for formatting numerical values:

pi = 3.1415926
print(f"Pi with two decimal places: {pi:.2f}")  # 3.14
Syntax Purpose Example Result
:.2f two decimal places (float) 3.14
:,.2f with thousand separator 1,234.56
:e exponential notation 3.14e+00
:.2e exponential with precision 3.14e+00
:% percentage representation 314%
:.2% percentage with precision 314.16%
:>10 right-align in a 10-char width 3.14
:<10 left-align in a 10-char width 3.14
:^10 center-align in a 10-char width 3.14
:0>5 zero-padding on the left to width 5 03.14

Alignment and Width Formatting

String formatting allows for creating neatly aligned data for tabular presentation:

value = 42
print(f"|{value:<10}|{value:^10}|{value:>10}|")
# Result: |42        |    42    |        42|

For more complex tables, you can use various padding characters:

items = [("Item A", 1250.75), ("Item B", 85.00), ("Item C", 12345.99)]
print(f"{'Name':<15} | {'Price':>10}")
print("-" * 28)
for item, price in items:
    print(f"{item:<15} | {price:>10.2f}")

Using f-strings with Collections and Objects

f-strings work effectively with various data structures:

user = {"name": "Anna", "balance": 1234.567, "currency": "USD"}
print(f"{user['name']}, your balance is: {user['balance']:.2f} {user['currency']}.")

# Working with lists and indexes
scores = [95, 87, 92, 88]
print(f"Average score: {sum(scores)/len(scores):.1f}")

# Formatting with conditional expressions
status = "active" if user['balance'] > 0 else "blocked"
print(f"Account status: {status}")

.format() Method: Versatility and Compatibility

Fundamentals of Using the .format() Method

The .format() method offers flexible string formatting capabilities and is compatible with older Python versions. This approach uses curly braces as placeholders that are replaced by the provided arguments:

template = "Hello, {0}. You have {1} new messages."
print(template.format("Olga", 5))

Named Arguments and Positional Parameters

The .format() method supports both positional and named arguments:

# Named arguments
print("{name} is studying at {university}".format(name="Vasya", university="MSU"))

# Mixed usage
print("{0} received a grade of {grade} in {1}".format("A student", "Mathematics", grade=5))

# Reusing arguments
print("{name} - {name} is a great name!".format(name="Alexander"))

Formatting Numbers with the .format() Method

The .format() method provides the same number formatting capabilities as f-strings:

price = 1234.567
print("{:>10.2f}".format(price))  # '   1234.57'
print("{:0>10.2f}".format(price)) # '0001234.57'
print("{:,}".format(1000000))     # '1,000,000'

Working with Dictionaries and Objects

The .format() method works effectively with dictionary unpacking:

data = {"product": "Laptop", "price": 58990.9, "discount": 0.15}
print("{product}: {price:.2f} USD (discount {discount:.1%})".format(**data))

# Working with object attributes
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

laptop = Product("MacBook", 120000)
print("Product: {0.name}, Price: {0.price:,.0f}".format(laptop))

Using Indexes and Slices

The .format() method allows accessing elements of collections by their index:

data = ["Ivan", "Petrov", 30]
print("First Name: {0[0]}, Last Name: {0[1]}, Age: {0[2]}".format(data))

scores = {"math": 95, "physics": 87, "chemistry": 92}
print("Math: {0[math]}, Physics: {0[physics]}".format(scores))

Classic %-formatting

Basics of %-formatting

The %-formatting style came to Python from the C language and is still used in some projects, especially in legacy codebases:

name = "Peter"
score = 95.5
print("%s scored %.1f points" % (name, score))

Main Format Specifiers

Specifier Meaning Example Usage
%s String "Name: %s" % "Ivan"
%d Integer "Age: %d" % 25
%f Floating-point number "Price: %f" % 19.99
%.2f Float with 2 decimal places "Precision: %.2f" % 3.14159
%x Hexadecimal number "Hex: %x" % 255
%o Octal number "Oct: %o" % 64
%e Exponential notation "Scientific: %e" % 1234

Advanced %-formatting Features

# Named parameters with a dictionary
data = {"name": "Anna", "age": 28, "salary": 75000.50}
print("Employee %(name)s, age %(age)d, salary %.2f" % data)

# Alignment and field width
print("Item: %-20s Price: %10.2f" % ("Bread", 25.50))
print("Item: %-20s Price: %10.2f" % ("Milk", 65.00))

Although %-formatting is not recommended for new projects, understanding its syntax is important for maintaining existing code and working with libraries that use it.

Advanced Number Formatting

Working with Decimals and Rounding

Python provides various ways to control the precision of numerical values:

import decimal

number = 1234.56789
print(f"{number:.2f}")  # 1234.57 (with rounding)
print(f"{number:.0f}")  # 1235 (to integer)

# Using decimal for precise arithmetic
precise_number = decimal.Decimal('1234.56789')
print(f"{precise_number:.3f}")  # 1234.568

# Different rounding methods
rounded_up = round(number, 3)  # 1234.568
truncated = int(number * 1000) / 1000  # 1234.567 (truncation)

Thousand Separators and Localization

Formatting large numbers with separators improves readability:

price = 1050000
population = 146748590

print(f"{price:,}")    # 1,050,000
print(f"{population:_}") # 146_748_590 (underscores as separators)

# Custom separators
formatted_price = f"{price:,}".replace(",", " ")  # 1 050 000
print(f"Price: {formatted_price} USD")

# Formatting in different currencies
usd_price = 15750.99
eur_price = 13250.50
print(f"USD: ${usd_price:,.2f}")
print(f"EUR: €{eur_price:,.2f}")

Percentage Representation and Ratios

ratio = 0.875
efficiency = 0.9234
growth = 0.156

print(f"Success rate: {ratio:.2%}")   # 87.50%
print(f"Efficiency: {efficiency:.1%}")  # 92.3%
print(f"Growth: {growth:+.2%}")      # +15.60% (with sign)

# Percentage change
old_value = 1000
new_value = 1150
change = (new_value - old_value) / old_value
print(f"Change: {change:+.1%}")  # +15.0%

Exponential and Scientific Notation

mass = 0.000056
distance = 150000000000
planck = 6.62607015e-34

print(f"Mass: {mass:.2e}")             # 5.60e-05
print(f"Distance: {distance:.2e}")       # 1.50e+11
print(f"Planck constant: {planck:.3e}") # 6.626e-34

# Alternative notation with a capital E
print(f"Large numbers: {distance:.2E}")  # 1.50E+11

Formatting in Different Number Systems

number = 255

print(f"Decimal: {number}")          # 255
print(f"Binary: {number:b}")           # 11111111
print(f"Octal: {number:o}")           # 377
print(f"Hexadecimal: {number:x}")  # ff
print(f"Hexadecimal (uppercase): {number:X}") # FF

# With prefixes
print(f"Binary with prefix: {number:#b}")    # 0b11111111
print(f"Octal with prefix: {number:#o}")  # 0o377
print(f"Hex with prefix: {number:#x}")    # 0xff

Alignment and Tabular Formatting

Creating Aligned Tables

Proper data alignment is critical for creating readable reports and tables:

# Data for the table
products = [
    ("Apples", 25.5, 120),
    ("Bananas", 40.1, 85),
    ("Oranges", 58.39, 200),
    ("Tangerines", 75.0, 150)
]

# Table header
print(f"{'Product':<12} | {'Price':>8} | {'Qty':>6} | {'Total':>8}")
print("-" * 45)

# Table rows
for name, price, quantity in products:
    total = price * quantity
    print(f"{name:<12} | {price:>8.2f} | {quantity:>6} | {total:>8.2f}")

Complex Alignment with Padding

# Different padding characters
value = 42
text = "Python"

print(f"{value:0>10}")   # 0000000042
print(f"{text:*^20}")    # *******Python*******
print(f"{value:+<15}")   # 42+++++++++++++

# Creating borders and separators
title = "SALES REPORT"
width = 50
print(f"{title:=^{width}}")  # Centering with equals sign padding

Dynamically Determining Column Width

data = [
    ("Short name", 123.45),
    ("A very long product name", 67.89),
    ("Medium item", 999.99)
]

# Determine the maximum width for each column
max_name_width = max(len(name) for name, _ in data)
max_price_width = max(len(f"{price:.2f}") for _, price in data)

print(f"{'Name':<{max_name_width}} | {'Price':>{max_price_width}}")
print("-" * (max_name_width + max_price_width + 3))

for name, price in data:
    print(f"{name:<{max_name_width}} | {price:>{max_price_width}.2f}")

Working with Text and String Methods

Case Changing Methods

Python provides numerous methods for controlling character case:

text = "python programming"

print(text.capitalize())     # Python programming
print(text.title())         # Python Programming
print(text.upper())         # PYTHON PROGRAMMING
print(text.lower())         # python programming
print(text.swapcase())      # PYTHON PROGRAMMING

# Case checking
print(text.islower())       # True
print(text.isupper())       # False
print(text.istitle())       # False

Centering and Padding Strings

text = "Python"

print(text.center(20))           # "       Python       "
print(text.center(20, "-"))      # "-------Python-------"
print(text.ljust(15, "."))       # "Python........."
print(text.rjust(15, "."))       # ".........Python"

# Stripping whitespace
spaced_text = "   Python   "
print(spaced_text.strip())       # "Python"
print(spaced_text.lstrip())      # "Python   "
print(spaced_text.rstrip())      # "   Python"

Splitting and Joining Strings

# Splitting strings
sentence = "Python,Java,JavaScript,C++"
languages = sentence.split(",")
print(languages)  # ['Python', 'Java', 'JavaScript', 'C++']

# Joining strings
result = " | ".join(languages)
print(result)  # Python | Java | JavaScript | C++

# Working with multiline text
multiline = """First line
Second line
Third line"""
lines = multiline.splitlines()
numbered = [f"{i+1:2d}: {line}" for i, line in enumerate(lines)]
print("\n".join(numbered))

Finding and Replacing in Strings

text = "Python is an excellent programming language"

# Finding substrings
print(text.find("language"))   # 29 (start index)
print(text.count("e"))         # 5 (number of occurrences)
print("Python" in text)        # True

# Replacing substrings
new_text = text.replace("Python", "Java")
print(new_text)  # Java is an excellent programming language

# Checking start and end
print(text.startswith("Python"))  # True
print(text.endswith("language"))  # True

Practical Applications and Templates

Generating HTML and Web Content

f-strings are ideal for creating HTML templates:

def generate_user_card(name, email, role, avatar_url=None):
    avatar = avatar_url or "default-avatar.png"
    
    html = f"""
    <div class="user-card">
        <img src="{avatar}" alt="Avatar" class="avatar">
        <div class="user-info">
            <h3>{name}</h3>
            <p class="email">{email}</p>
            <span class="role {role.lower()}">{role}</span>
        </div>
    </div>
    """
    return html

user_html = generate_user_card("Anna Ivanova", "anna@example.com", "Admin")
print(user_html)

Creating Configuration Files

def generate_config(database_host, database_port, debug_mode, api_keys):
    config = f"""
[database]
host = {database_host}
port = {database_port}
timeout = 30

[application]
debug = {str(debug_mode).lower()}
log_level = {'DEBUG' if debug_mode else 'INFO'}

[api]
"""
    
    for service, key in api_keys.items():
        config += f"{service}_key = {key}\n"
    
    return config

config_content = generate_config(
    "localhost", 
    5432, 
    True, 
    {"google": "abc123", "stripe": "sk_test_xyz"}
)
print(config_content)

Generating Reports and Logs

import datetime

def generate_sales_report(sales_data, period):
    current_time = datetime.datetime.now()
    total_sales = sum(item['amount'] for item in sales_data)
    total_items = len(sales_data)
    
    report = f"""
{'='*60}
                    SALES REPORT
{'='*60}
Period: {period}
Date Created: {current_time.strftime('%Y-%m-%d %H:%M')}

Overall Statistics:
- Total Transactions: {total_items:,}
- Total Amount: ${total_sales:,.2f}
- Average Check: ${total_sales/total_items:,.2f}

{'='*60}
SALES DETAILS
{'='*60}
"""
    
    for i, sale in enumerate(sales_data, 1):
        report += f"{i:3d}. {sale['product']:<20} ${sale['amount']:>10.2f}\n"
    
    report += f"{'='*60}\n"
    return report

sales = [
    {'product': 'Laptop', 'amount': 750.00},
    {'product': 'Mouse', 'amount': 15.00},
    {'product': 'Keyboard', 'amount': 35.00}
]

print(generate_sales_report(sales, "January 2024"))

Formatting SQL Queries

def build_select_query(table, columns=None, where_conditions=None, limit=None):
    columns_str = ", ".join(columns) if columns else "*"
    
    query = f"SELECT {columns_str}\nFROM {table}"
    
    if where_conditions:
        conditions = " AND ".join(f"{key} = '{value}'" for key, value in where_conditions.items())
        query += f"\nWHERE {conditions}"
    
    if limit:
        query += f"\nLIMIT {limit}"
    
    return query

sql = build_select_query(
    table="users",
    columns=["id", "name", "email"],
    where_conditions={"status": "active", "role": "admin"},
    limit=10
)
print(sql)

Creating API Responses in a JSON-like Format

def format_api_response(status, data=None, error=None, pagination=None):
    response = f'{{\n  "status": "{status}"'
    
    if data is not None:
        response += f',\n  "data": {data}'
    
    if error:
        response += f',\n  "error": "{error}"'
    
    if pagination:
        response += f',\n  "pagination": {{\n    "page": {pagination["page"]},\n    "total": {pagination["total"]}\n  }}'
    
    response += '\n}'
    return response

api_result = format_api_response(
    "success",
    data='[{"id": 1, "name": "User1"}]',
    pagination={"page": 1, "total": 100}
)
print(api_result)

Performance Comparison of Methods

Benchmarking Different Approaches

Performance is an important factor when choosing a formatting method:

import timeit

name = "Alice"
age = 30
salary = 50000.75

# Test setup
test_data = {
    'f-string': 'f"Name: {name}, Age: {age}, Salary: {salary:.2f}"',
    'format': '"Name: {}, Age: {}, Salary: {:.2f}".format(name, age, salary)',
    'percent': '"Name: %s, Age: %d, Salary: %.2f" % (name, age, salary)',
}

# Run tests
results = {}
for method, code in test_data.items():
    time_taken = timeit.timeit(code, globals=globals(), number=1000000)
    results[method] = time_taken

# Print results
print("Performance Test Results (1,000,000 iterations):")
print("-" * 60)
for method, time_taken in sorted(results.items(), key=lambda x: x[1]):
    print(f"{method:<12}: {time_taken:.4f} seconds")

Recommendations for Choosing a Method

In practice, f-strings demonstrate the best performance and code readability. This is especially important in high-load applications and when working in a team where code readability is critical for project maintenance and development.

The choice of formatting method depends on specific requirements:

  • f-strings: For most modern projects using Python 3.6+.
  • .format() method: For templates, dynamic formatting, or compatibility with Python 2.7/3.5.
  • %-formatting: Only for maintaining legacy code.

Conclusion

String formatting in Python is much more than simply inserting values into text. It is a powerful tool for creating readable, precise, and manageable information output, playing a key role in the development of high-quality software.

f-strings are the modern standard and are recommended for use in most tasks due to their readability, performance, and functionality. The .format() method remains a useful tool for dynamic formatting, working with templates, and ensuring compatibility with older Python versions. Classic %-formatting should only be used when maintaining legacy systems is necessary.

Proper use of string formatting makes code more understandable and maintainable, user interfaces more attractive, and data more presentable. This skill is fundamental for any Python developer and deserves continuous improvement in daily practice.

Correct string formatting contributes to creating professional applications, high-quality reports, and user-friendly interfaces. The time invested in learning these techniques pays off in improved code quality and development productivity.

Frequently Asked Questions (FAQ)

Which is better to use: f-strings or the .format() method?

For modern projects on Python 3.6+, it is recommended to use f-strings. They provide better code readability, higher performance, and a more intuitive syntax. The .format() method should be used when dynamic formatting is required, when working with templates, or to ensure compatibility with older Python versions.

How do I correctly round a number to a specific number of decimal places?

To round a number to 3 decimal places, use the syntax f"{value:.3f}". This approach automatically rounds the number according to mathematical rules. For more control over rounding, you can use the round() function or the decimal module for precise arithmetic.

How do I display a number in percentage format?

To display a number in percentage format, use the % specifier: f"{ratio:.2%}". This automatically multiplies the value by 100 and adds a percent sign. For example, a value of 0.875 will be displayed as 87.50%.

How can I create a neat, aligned table from strings?

To create tables, use alignment specifiers: < for left alignment, > for right alignment, and ^ for centering. For example, f"{value:<10}" will left-align the value in a field 10 characters wide. To dynamically determine column widths, calculate the maximum length of the data in each column beforehand.

What should I do if I am using a Python version older than 3.6?

For Python versions below 3.6, use the .format() method, which has been available since Python 2.7. This method provides most of the features of f-strings, albeit with a less convenient syntax. Avoid %-formatting in new code, even when working with older Python versions.

How can I format large numbers with thousand separators?

Use the , specifier to add commas as thousand separators: f"{large_number:,}". To use other separators (like spaces), you can apply the .replace() method: f"{number:,}".replace(",", " ").

Can I use f-strings for multiline templates?

Yes, f-strings support multiline templates using triple quotes. This is particularly convenient for generating HTML, SQL queries, configuration files, and other structured text. All variables and expressions within curly braces will be processed correctly.

News