DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Pydantic: Simplifying Data Validation in Python
  • Bridging Graphviz and Cytoscape.js for Interactive Graphs
  • Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide
  • How to Simplify Complex Conditions With Python's Match Statement

Trending

  • How to Format Articles for DZone
  • Strategies for Securing E-Commerce Applications
  • Simplifying Multi-LLM Integration With KubeMQ
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  1. DZone
  2. Data Engineering
  3. Data
  4. Python String Format Examples

Python String Format Examples

In this brief introduction to string formatting in Python, we will explore live examples of string concatenation, string substitution, and additional formatting methods for common string operations.

By 
Kellet Atkinson user avatar
Kellet Atkinson
·
Jan. 23, 20 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
48.6K Views

Join the DZone community and get the full member experience.

Join For Free

Anytime you are programming something to be human-readable, you are bound to encounter lots of instances where you will need to format strings. Luckily Python offers a lot of different approaches for tackling strings. While I would not consider all of them best practices, it is always good to know what you can and cannot do. Below we will take a look at the many different options available for formatting strings in Python.

Basic String Concatenation

The most basic way to format a string in Python is with simple concatenation.

Python
 




xxxxxxxxxx
1


 
1
days = 28
2
month = 'February"
3

          
4
my_string = month + ' is the shortest month of the year, with '+ str(days) + ' days.'



This approach is simple, but it is messy, inefficient, and prone to error (ever forget the spaces?), especially for complex, dynamic strings.

You may also be familiar with the % operator (called a modulo), which allows you to perform string replacements like this (using a predefined variable "month" for substitution):

Python
 




xxxxxxxxxx
1


 
1
month = 'February'
2

          
3
my_string = '%s is the shortest month of the year' % month



While also valid, this approach is more or less obsolete (Python 3 introduced the format() method, which was back-ported to Python 2.7).

Introduction to the format() Method

That brings us to Python's native string format() method. Introduced in Python 3, this method provides a simple way to construct and format strings with dynamic substitutions.  Once you understand the basic syntax, this method offers a flexible way to construct strings that also happens to leave your code looking much cleaner (in my opinion).

With the format() method, there are two primary substitution types, by index and by keyword.

Substitution by Index

By passing in an index (or positional argument), the format method will allow you to insert individual or multiple items from a list based on their index. In this example, 'world' is the first (index 0) item in our list, so it gets inserted.

Python
 




xxxxxxxxxx
1


 
1
my_string = 'Hello {0}!'.format('world','friend','there')



When we print our string to the console, we get: Hello world!

To see another example, try the interactive example below:

Example: Try changing the index values in the string!


Substitution by Keyword

The other approach is to use a keyword argument for substitution, where the keyword references the key in a key-value pair.

Python
 




xxxxxxxxxx
1


 
1
my_string = "This month is {f}!".format(f='February')



If we print our string to the console, we get: This month is February!

Example: Using Variables

Number Formatting

The previous examples work for inserting strings into strings, but what if you want to insert a numeric value?  For that, there are additional formatting specifiers that are appended to the value to specify the desired output format. 

Python
 




xxxxxxxxxx
1


 
1
months = 12
2
days = 365
3
avg_days_per_month = days/months
4

          
5
# The ':g' specifier formats the value as a 'general' number.
6
myString='On average, the months in a year have {0:g}.'.format(avg_days_per_month)



(If you don't include a format specifier for an integer, it will default to "general" format.)

Specifier Formats Number As
d Decimal integer
g | G General number. Defaults to 6 levels of precision, or the min number of relevant levels.
 | "G" functions the same as "g" except that large numbers will be formatted with "E".
f Fixed point number. Defaults to 6 levels of precision.
e | E Scientific notation
% Converts value to a percentage
n Same as 'g' but uses the seperators of the current locale.
Specifier Converts Number To
h | H Hexidecimal (lower case | upper case)
o Octal
b Binary
c

Unicode



F-string (Literal String Interpolation, Oh My!)

With the release of Python 3.6, we were introduced to F-strings.

As their name suggests, F-strings begin with "f" followed by a string literal. We can insert values dynamically into our strings with an identifier wrapped in curly braces, just like we did in the format() method. However, instead of an index that represents our value's position in a list or a key that maps to our value, we can use a variable name as our identifier. 

Take the following example: 

Python
 




xxxxxxxxxx
1


 
1
month = 'February'
2

          
3
my_string = f'This month is {month}!'
4
print(my_string)



Here, our month variable is placed directly into our string. {month} is then replaced with month's value, "February," when the F-string is evaluated. So, when my_string prints to our terminal, we get This month is February!. This removes some of the ambiguity that the previous methods added to string formatting. After all, why create a placeholder to represent a value that we reference later if we can use a single variable instead?


Another advantage of F-strings is that we don't have to account for variable types. Notice that num_normal_days in the example above is an integer, 28. Previously, we would have had to use placeholders like %d or :g in order to add a numeric type to our string. With F-string, we don't have to tell our program that it's going to be looking at an integer inside of a string. Let's let Python do what it's good at — making our lives easier. 

Note: When using properties of objects with F-strings, make sure to avoid dot notation and instead use braces. For example, if I had an object called month and wanted to access its property, days, I would use months['days'] as opposed to month.days.

Additional Python String Methods

Python also offers a set of methods to help you programmatically transform your strings. Here is a list of a few methods worth making note of:

Method Result
capitalize() Capitalizes the first letter of the string
casefold() Returns the string in all lowercase (useful for string matching according to the python documentation)
count() Counts all instances of a substring
upper() Returns the string in all uppercase letters
split() Splits string on designated seperator
encode() Returns an encoded string
swapcase() Swaps the case of each letter in the string


More methods can be found in Python's String documentation.

Note: If you're interested in another formatting method in Python, check out their docs on String Templates. 


Further Reading

  • 10 Reasons to Learn Python in 2019.
Strings Data Types Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Pydantic: Simplifying Data Validation in Python
  • Bridging Graphviz and Cytoscape.js for Interactive Graphs
  • Getting Started With Snowflake Snowpark ML: A Step-by-Step Guide
  • How to Simplify Complex Conditions With Python's Match Statement

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!