Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Mastering Python F-String Formatting: A Trader’s Guide

7 min read

Python f-string formatting lets you put variables and expressions straight inside a string with f"...{value:format}", and the part after the colon controls decimals, commas, percentages, padding and dates. For traders that means one short line can print a price to two decimals, a volume with separators, a return as a percentage or a timestamp for a report. Below are 18 trading-focused snippets plus a format cheat sheet.

What is Python f-string formatting?

F-String, introduced in Python 3.6, stands for “Formatted String Literals.” It’s a way to format strings in Python, allowing for easier and more readable string formatting. F-strings are recognizable by their prefix f before the opening quotation mark of a string. They use curly braces {} to evaluate variables or expressions directly within the string.

Example

name = "NIFTY"
price = 19500
formatted_string = f"The current index of {name} is {price}."
print(formatted_string)

Output: The current index of NIFTY is 19500.

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls

In this example, the variables name and price are directly inserted into the string using their variable names inside the curly braces.

Key takeaways

  • Prefix the string with f and place expressions in {}.
  • Add a format spec after a colon: {price:.2f}, {volume:,}, {change:.2%}, {dt:%Y-%m-%d}.
  • Use <, > and ^ with a width to build aligned tables.
  • Use {value=} (Python 3.8+) to debug variables quickly.
  • The built-in , separator uses western grouping; for lakhs and crores use a helper function (shown below).

Why Should Traders Learn F-String Formatting in Python?

Trading involves dealing with a lot of data, including prices, volumes, dates, and percentages. F-strings allow traders to format this data succinctly and clearly in their Python scripts or Jupyter notebooks. For traders who rely on Python for data analysis, report generation, or algorithmic trading, learning f-string formatting is a valuable skill that enhances their coding efficiency.

Traders often need to generate dynamic reports or real-time dashboards. F-strings make it simple to integrate variables and expressions directly within string literals, which is ideal for creating up-to-date content.

1. Basics of F-String Formatting

Snippet 1: Basic f-string syntax.

name = "Bank Nifty"
print(f"The index we are analyzing is {name}.")

Output: The index we are analyzing is Bank Nifty.

Snippet 2: Formatting numbers with commas.

volume = 78456385
print(f"Total traded volume: {volume:,}")

Output: Total traded volume: 78,456,385

2. Formatting Financial Figures

Snippet 3: Formatting currency adjusted to two decimals

price = 350.4
print(f"The closing price was ${price:.2f}")

Output: The closing price was $350.40

Snippet 4: Formatting local currency(INR).

import locale

# Set the locale to Indian English
locale.setlocale(locale.LC_ALL, 'en_IN')

# Your currency amount
amount = 1234567.89

# Format the amount as currency using f-string and locale.currency()
formatted_amount = locale.currency(amount, grouping=True)

print(f"The formatted amount in Indian currency is: {formatted_amount}")

Output: The formatted amount in Indian currency is: ₹ 12,34,567.89

Note (2026): locale.setlocale(locale.LC_ALL, 'en_IN') only works if that locale is installed on your machine, and the name differs by system (for example en_IN.UTF-8 on many Linux servers). If you get locale.Error: unsupported locale setting, use the pure Python helper below. It formats amounts in lakhs and crores on any system:

Updated version (2026): Indian number format without locale

def format_inr(amount: float) -> str:
    """Format a number in the Indian system (lakhs and crores) without locale."""
    sign = "-" if amount < 0 else ""
    whole, decimals = f"{abs(amount):.2f}".split(".")
    if len(whole) > 3:
        head, last3 = whole[:-3], whole[-3:]
        groups = []
        while len(head) > 2:
            groups.insert(0, head[-2:])
            head = head[:-2]
        if head:
            groups.insert(0, head)
        whole = ",".join(groups + [last3])
    return f"{sign}₹{whole}.{decimals}"


print(format_inr(1234567.89))   # ₹12,34,567.89
print(format_inr(45678901.5))   # ₹4,56,78,901.50
print(format_inr(-999.5))       # -₹999.50

Snippet 5: Using percentage format.

change = 0.0534
print(f"Price change: {change:.2%}")

Output: Price change: 5.34%

Format specifier cheat sheet

NumberFormatOutputDescription
3.1415926{:.2f}3.14Format float 2 decimal places
3.1415926{:+.4f}+3.1416Format float 4 decimal places with sign
-1{:+.2f}-1.00Format float 2 decimal places with sign
2.71828{:.0f}3Format float with no decimal places
4{:02}04Pad number with zeros (left padding, width 2)
4{:x<4d}4xxxPad number with x’s (right padding, width 4)
10{:x>6d}xxxx10Pad number with x’s (left padding, width 6)
5000000{:,}5,000,000Number format with comma separator
0.35{:.2%}35.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
11{:11d} 11Right-aligned (default for numbers, width 11)
11{:<11d}11Left-aligned (width 11)
11{:^11d} 11Center aligned (width 11)

The full syntax is documented in the Python format specification mini-language. The same rules apply to f-strings and to str.format().

3. Date and Time in Trading

Snippet 6: Formatting current date

from datetime import datetime
current_time = datetime.now()
print(f"Report generated on {current_time:%Y-%m-%d %H:%M}")

Output: Report generated on 2023-11-15 09:10

Snippet 7: Time delta in reports.

from datetime import timedelta
yesterday = datetime.now() - timedelta(days=1)
print(f"Data from: {yesterday:%Y %B, %d}")

Output: Data from: 2023 November, 14

List of Date & Time Formatting

DirectiveDescriptionExample
%aWeekday, short versionWed
%AWeekday, full versionWednesday
%wWeekday as a number 0-6, 0 is Sunday3
%dDay of month 01-3131
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth as a number 01-1212
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2317
%IHour 00-1205
%pAM/PMPM
%MMinute 00-5941
%SSecond 00-5908
%fMicrosecond 000000-999999548513
%zUTC offset+0530
%ZTimezoneIST
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week, 00-5352
%WWeek number of year, Monday as the first day of week, 00-5352
%cLocal version of date and timeMon Dec 31 17:41:00 2018
%CCentury20
%xLocal version of date12/31/18
%XLocal version of time17:41:00
%%A % character%

4. Handling Stock Data

Snippet 8: Displaying stock price with color coding.

stock_price_change = -2.45
color = 'red' if stock_price_change < 0 else 'green'
print(f"Change: {stock_price_change} ({color})")

Output: Change: -2.45 (red)

5. Advanced Formatting for Reporting

Snippet 9: Conditional formatting based on performance.

performance = 0.05
status = "Good" if performance > 0.04 else "Average"
print(f"Monthly performance: {performance:.2%} - {status}")

Output: Monthly performance: 5.00% - Good

Snippet 10: Dynamic precision in reporting.

precision = 3
rate = 5.12345
print(f"Interest rate: {rate:.{precision}f}")

Output: Interest rate: 5.123

6. Formatting in Trading Algorithms

Snippet 11: Displaying algorithmic trade decisions.

action = "BUY"
quantity = 500
print(f"Action: {action}, Quantity: {quantity}")

Output: Action: BUY, Quantity: 500

Snippet 12 : Iterating over a list

If you have a list of stock prices and you want to print them out with some additional text, you can iterate over the list using a for loop:

# Example list of stock prices
stock_prices = [150.5, 200.3, 98.7, 143.6]

# Iterate over the list and print each price
for price in stock_prices:
    print(f"Current stock price: ${price:.2f}")

Output:

Current stock price: $150.50
Current stock price: $200.30
Current stock price: $98.70
Current stock price: $143.60

Snippet 13 : Accessing Specific List Elements

If you want to format and print specific elements from the list, you can access them by their index:

# Example list of currencies
currencies = ["USD", "EUR", "JPY", "INR"]

# Access and print specific elements
print(f"The first currency in the list is {currencies[0]}")
print(f"The fourth currency in the list is {currencies[3]}")

Output:

The first currency in the list is USD
The fourth currency in the list is INR

7. Real-time Data Display

Snippet 14: Read the data from dictionary

stocks = {
    "AAPL": 150.50,
    "MSFT": 295.00,
    "GOOGL": 2820.80
}

# Iterate over the dictionary and use f-string for formatting
for symbol, price in stocks.items():
    print(f"Stock: {symbol}, Price: ${price:.2f}")

Output:

Stock: AAPL, Price: $150.50
Stock: MSFT, Price: $295.00
Stock: GOOGL, Price: $2820.80

Snippet 15 : Read the data from json

First, let’s assume you have a JSON string like this:

[
    {"symbol": "AAPL", "price": 150.50},
    {"symbol": "MSFT", "price": 295.00},
    {"symbol": "GOOGL", "price": 2820.80}
]

Now, let’s write a Python snippet to parse this JSON and use f-strings to format and print this data:

import json

# JSON data as a string
json_data = '''
[
    {"symbol": "AAPL", "price": 150.50},
    {"symbol": "MSFT", "price": 295.00},
    {"symbol": "GOOGL", "price": 2820.80}
]
'''

# Parse the JSON data into a Python list
stocks = json.loads(json_data)

# Iterate over the list and use f-string for formatting
for stock in stocks:
    print(f"Stock: {stock['symbol']}, Price: ${stock['price']:.2f}")

Output:

Stock: AAPL, Price: $150.50
Stock: MSFT, Price: $295.00
Stock: GOOGL, Price: $2820.80

In this snippet:

  • json.loads is used to parse the JSON string into a Python object (in this case, a list of dictionaries).
  • An f-string is used within a loop to format and print out each stock’s symbol and price. The price is formatted to two decimal places.

Snippet 16: Creating a dynamic ticker display.

tickers = ["AAPL", "MSFT", "GOOGL"]
prices = [157, 242, 2732]
for ticker, price in zip(tickers, prices):
    print(f"{ticker:5}: ${price:.2f}")

Output:
AAPL : $157.00
MSFT : $242.00
GOOGL: $2732.00

8. Portfolio Analysis

Snippet 17: Displaying asset allocation.

allocations = {"Stocks": 60, "Bonds": 30, "Cash": 10}
for asset, percentage in allocations.items():
    print(f"{asset:6}: {percentage}%")

Output:

Stocks: 60%
Bonds : 30%
Cash : 10%

Snippet 18 : Stock Pricing in Table Format

stock_data = [
    {"Symbol": "AAPL", "Price": 150.50, "Change": 1.25},
    {"Symbol": "MSFT", "Price": 295.00, "Change": -0.85},
    {"Symbol": "GOOGL", "Price": 2820.80, "Change": 0.55}
]

# Determine column widths
symbol_width = max(len(stock["Symbol"]) for stock in stock_data) + 2
price_width = max(len(f"{stock['Price']:.2f}") for stock in stock_data) + 2
change_width = max(len(f"{stock['Change']:.2f}") for stock in stock_data) + 2

# Print table header
print(f"{'Symbol':<{symbol_width}}{'Price':<{price_width}}{'Change':<{change_width}}")

# Print table rows
for stock in stock_data:
    symbol, price, change = stock["Symbol"], stock["Price"], stock["Change"]
    print(f"{symbol:<{symbol_width}}{price:<{price_width}.2f}{change:<{change_width}.2f}%")

This code will output a table like:

Symbol Price   Change
AAPL   150.50  1.25 %
MSFT   295.00 -0.85 %
GOOGL  2820.80 0.55 %
  • The widths for the ‘Symbol’, ‘Price’, and ‘Change’ columns are calculated based on the longest string that will be printed in each column.
  • The table header is printed first, using the calculated widths to align the column names.
  • Each row of stock data is then printed, formatting the ‘Price’ and ‘Change’ to two decimal places.
  • The < in the f-string format specification aligns the text to the left, ensuring a neatly aligned table.

This approach dynamically adjusts to the data, creating a well-formatted and readable stock market data table.

Note: when you run Snippet 18 exactly as written, each column is left-aligned and padded, so the output has a little more spacing than the sample above and the % sign follows the padded change value. For financial tables it usually reads better to right-align numbers. Here is a tidier variant:

Updated version (2026): right-aligned stock table

stock_data = [
    {"Symbol": "AAPL", "Price": 150.50, "Change": 1.25},
    {"Symbol": "MSFT", "Price": 295.00, "Change": -0.85},
    {"Symbol": "GOOGL", "Price": 2820.80, "Change": 0.55},
]

print(f"{'Symbol':<8}{'Price':>10}{'Change %':>10}")
print("-" * 28)
for s in stock_data:
    print(f"{s['Symbol']:<8}{s['Price']:>10,.2f}{s['Change']:>+10.2f}")

Output:

Symbol       Price  Change %
----------------------------
AAPL        150.50     +1.25
MSFT        295.00     -0.85
GOOGL     2,820.80     +0.55

More f-string tricks traders use

These features were added after the original snippets and are useful when debugging strategies or building logs:

symbol = "NIFTY"
ltp = 24351.456
pnl = -1520.5

# Self-documenting expressions (Python 3.8+)
print(f"{ltp=}")
print(f"{ltp = :.2f}")

# Literal curly braces: double them
print(f"{{'symbol': '{symbol}'}}")

# Signed P&L, thousands separator, fixed width
print(f"P&L: {pnl:>+12,.2f}")

# Python 3.12+: reuse the same quote type inside the braces
quote = {"symbol": "NIFTY", "ltp": 24351.45}
print(f"{quote["symbol"]} last traded at {quote["ltp"]:,.2f}")

Output:

ltp=24351.456
ltp = 24351.46
{'symbol': 'NIFTY'}
P&L:    -1,520.50
NIFTY last traded at 24,351.45
  • {ltp=} prints the expression and its value, which is handy for quick debugging.
  • Double braces {{ }} print literal curly braces, for example when building JSON-like text.
  • Since Python 3.12 (PEP 701) you can reuse the same quote character inside the braces. On older versions use different quotes, as in Snippet 15.

Python f-string formatting vs format() vs %

MethodExampleWhen to use
f-stringf”{price:.2f}”Default choice in Python 3.6+: shortest and fastest to read
str.format()“{:.2f}”.format(price)Templates stored separately from the values (for example in a config file)
% operator“%.2f” % priceOld code, and the logging module, which formats lazily with %s style

Common mistakes in Python f-string formatting

  • Forgetting the f prefix, which prints the braces literally.
  • Using :, and expecting Indian grouping. It gives 1,234,567, not 12,34,567.
  • Formatting numbers too early. Keep floats as numbers for calculations and format only when printing.
  • Building SQL queries or broker API payloads with f-strings. Use query parameters and JSON libraries instead.
  • Hard-coding $ for Indian instruments. Use ₹ or the helper above for INR values.

Next, put these formats to work with Pandas DataFrames for traders, fetching Nifty 50 symbols using Python and plotting candlestick charts in Python. If you also write AmiBroker code, see raw strings in AmiBroker.

Frequently Asked Questions

How do I format a float to 2 decimal places in a Python f-string?

Use f"{value:.2f}". For example f"{350.4:.2f}" gives 350.40. Add a comma for separators: f"{value:,.2f}".

How do I escape curly braces in an f-string?

Double them. f"{{price}}" prints {price} literally, while f"{{{price}}}" prints the value inside braces.

How do I show a percentage with an f-string?

Use the % type: f"{0.0534:.2%}" gives 5.34%. The value is multiplied by 100 automatically.

Which Python version supports f-strings?

F-strings were introduced in Python 3.6. The = debugging specifier needs 3.8, and reusing the same quotes inside braces needs 3.12.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More