Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

String formatting in Python


Tutorial 6.2 - String Manipulation

String formatting


String formatting in Python is the process of creating formatted strings by inserting values into placeholders within a string. Python provides multiple ways to achieve string formatting, each with its own syntax and benefits. Let's explore the different string formatting methods:  

1. Using `%` Operator:  

The `%` operator is an older method of string formatting. It uses placeholders like `%s` for strings, `%d` for integers, and `%f` for floating-point numbers.

name = "Alice"
age = 30
formatted = "My name is %s and I am %d years old." % (name, age)

2. Using `.format()` Method:  

The `.format()` method provides more flexibility in formatting strings. It uses curly braces `{}` as placeholders.

name = "Alice"
age = 30
formatted = "My name is {} and I am {} years old.".format(name, age)

You can also specify the order of placeholders explicitly.

formatted = "My name is {0} and I am {1} years old.".format(name, age)

3. Using f-strings (Formatted String Literals):  

Introduced in Python 3.6, f-strings provide a concise and readable way to format strings. They use an `f` prefix before the string and use curly braces`{}` to insert expressions directly into the string.

name = "Alice"
age = 30
formatted = f"My name is {name} and I am {age} years old."

4. Using `str.format_map()` for Dictionaries:  

You can use `str.format_map()` to format strings using dictionary values.

person = {"name": "Alice", "age": 30}
formatted = "My name is {name} and I am {age} years old.".format_map(person)

5. Using Template Strings:  

Python's `string.Template` class provides another way to do string formatting using placeholders surrounded by dollar signs.

from string import Template

template = Template("My name is $name and I am $age years old.")
formatted = template.substitute(name=name, age=age)

String formatting methods like f-strings are generally preferred due to their readability, simplicity, and support for complex expressions. However, the choice of formatting method can depend on the Python version you're using and your specific needs.


This post first appeared on Tsarde, please read the originial post: here

Share the post

String formatting in Python

×

Subscribe to Tsarde

Get updates delivered right to your inbox!

Thank you for your subscription

×