In this Python tutorial, we will discuss, Pyhton string format() method, and also we will see a few Python string formatting examples.
There are several ways to format strings in Python, which are shown below:
- Using f-strings
- Using % operator
- Using the format() method
- Using string.Template class
- Using the str.format_map() method
- Using the str.maketrans() and str.translate()
- Using string concatenation
- Using the %r formatter
Python string format() method
Now, we will see python string format methods.
The Python string format() method formats the specified value and insert them inside the string placeholder. The placeholder is defined by using curly brackets “{ }” and the price is fixed, with two decimal format.
val = "Its only {price:.2f} Rupees!"
print(val.format(price = 84))
To get the output, I have used print(val.format(price = 84)). You can refer to the below screenshot for the output.
This is how to use the format() method in Python string.
The Python string format() method allows the formatting of the selected parts of a string. We use format to make sure that the string will display as expected.
To control such value, add a placeholder curly bracket {} in the text and then run the values through the format() method.
Example:
roll = 101
msg = "The roll start from {} "
print(msg.format(roll))
To get the output, I have used print(msg.format(roll)). You can refer to the below screenshot for the output.
This is how we can do string formatting in Python.
Python String Formatting using Various Methods
String formatting is an essential concept for Python developers as it allows for the creation of dynamic strings that can be customized to include variables, values, and other data types.
Method-1: Using f-strings
Python F-strings provide a concise and readable way to embed expressions inside string literals. The expressions inside the braces are evaluated at runtime and the result is formatted into the string.
# Assigns the string value 'USA' to the variable name
name = 'USA'
# Uses an f-string to format and print out a message that includes the value of the variable name
# The {} brackets indicate where the value of the variable should be inserted in the string
# The f before the opening quote tells Python to interpret any expressions inside the string
print(f'Country name is {name}.')
The above creates a variable called name and assigns it the value ‘USA’.
- F-strings in Python are a way to embed expressions inside string literals, allowing you to create dynamic output messages.
- In this case, the curly braces {} are used to indicate where the value of the name variable should be inserted in the string. The . at the end of the string is used to denote the end of the sentence
Output: Country name is USA.
Method-2: Using % operator
The % operator is an older way of formatting strings in Python. In this method, the % operator is followed by a format string containing placeholders (%s, %d, %f, etc.) and a tuple of values to be formatted.
# Assigns the string value 'USA' to the variable name
name = 'USA'
# Uses string formatting with the % operator to print out a message that includes the value of the variable name
# The %s placeholder is used to indicate where the value of the variable should be inserted in the string
# The %(name) syntax specifies that the value of the name variable should be used to fill in the %s placeholder
print('Country name is %s' %(name))
The above code uses string formatting with the % operator to insert the value of the name variable into a message string.
- %s is a placeholder for a string value, and the (name) syntax specifies that the value of the name variable should be used to fill in the %s placeholder. The resulting output message will be “Country name is USA.”.
Output: Country name is USA
Method-3: Using the format() method
The Python format() method is another way of formatting strings in Python. In this method, the format() method is called on a string and the placeholders {} are used to specify where the values should be inserted.
# Define a string variable 'name' and assign it the value 'Canada'
name = 'Canada'
# Print a formatted string that includes the value of the 'name' variable
print('Country name is {}'.format(name))
The above code defines a string variable ‘name’ and assigns it the value ‘Canada’.
- It then uses the print() function to output a formatted string that includes the value of the ‘name’ variable.
- The curly braces {} are used as placeholders for the value of the ‘name’ variable, and the .format() method is used to insert the value into the string.
Output: Country name is Canada
Method-4: Using string.Template class
The Python string.Template class provides a way to create templates with placeholders that can be replaced with values at runtime.
# Import the Template class from the string module
from string import Template
# Assigns the string value 'Canada' to the variable name
name = 'Canada'
# Create a new Template object and assign it to the variable template
# The template string includes a variable named 'name' enclosed in dollar signs
template = Template('Country name is $name')
# Use the substitute() method to replace the 'name' variable with the value of the name variable
# The name parameter inside the substitute method specifies the value to use for the 'name' variable in the template
print(template.substitute(name=name))
The above code uses the string.Template class to create a template string that includes a variable named ‘name’ enclosed in dollar signs.
- The Template class provides a way to substitute values into a template string at runtime. The substitute() method is used to replace the ‘name’ variable with the value of the name variable, specified as an argument to the method.
Output: Country name is Canada
Method-5: Using the str.format_map() method
The format_map() method in Python is similar to the format() method, but instead of passing values directly, it takes a dictionary as an argument. The keys in the dictionary are used as placeholders in the string and the values are used to replace the placeholders.
# Create a dictionary with a single key-value pair
# The key is 'name' and the value is 'United Kingdom'
country = {'name': 'United Kingdom'}
# Use string formatting with the format_map() method to print out a message that includes the value of the 'name' key in the country dictionary
# The {name} placeholder is used to indicate where the value of the 'name' key should be inserted in the string
# The format_map() method substitutes values into the string using the key-value pairs in the given dictionary
print('Country name is {name} '.format_map(country))
The above code is using the format_map() method to insert the value of a key in a dictionary into a string.
Specifically, it’s using the dictionary {‘name’: ‘United Kingdom’} and inserting the value associated with the key ‘name’ into the string “Country name is {name} “.
{name} is a placeholder that is replaced by the value associated with the key ‘name’ in the dictionary. Since the value associated with the ‘name’ key is ‘United Kingdom’, that value is inserted into the output message.
Output: Country name is United Kingdom
Method-6: Using the str.maketrans() and str.translate()
The Python maketrans() method is used to create a translation table, which can be used with the translate() method to replace characters in a string.
# Assigns the string value 'United Kingdom' to the variable s
s = 'United Kingdom'
# Create a translation table using the str.maketrans() method
# The translation table maps the character 'o' to the character '0'
data = str.maketrans('o', '0')
# Use the translate() method to create a new string where all occurrences of 'o' are replaced with '0'
# The translate() method replaces characters in the string according to the translation table provided as an argument
s = s.translate(data)
# Print the resulting string, which should have all 'o' characters replaced with '0'
print(s)
The above code creates a string variable s with the value ‘United Kingdom’.
- It then creates a translation table using the str.maketrans() method, which maps the character ‘o’ to the character ‘0’. The str.maketrans() method creates a translation table that can be used to replace characters in a string.
- then uses the translate() method to create a new string where all occurrences of the character ‘o’ in the original string are replaced with the character ‘0’.
Output: United Kingd0m
Method-7: Using string concatenation
String concatenation involves joining multiple strings together to create a single string in Python. This can be useful for simple string formatting tasks.
# Define a string variable 'name' and assign it the value 'James'
name = 'James'
# Print a string that includes the value of the 'name' variable using concatenation
print('My name is ' + name)
The above code defines a string variable called “name” and assigns it the value “James”.
- The print() function is then used to output a string to the console. The string “My name is ” is concatenated with the value of the “name” variable using the + operator. This produces the string “My name is James”.
Output: My name is James
Method-8: Using the %r formatter
The %r formatter is similar to the %s formatter, but it uses the repr() function in Python to display the object, rather than the str() function. This can be useful for debugging.
# Assigns the string 'Jhon' to the variable s
s = 'Jhon'
# Prints a message to the console using string formatting with the % operator
# %r is used to insert a string representation of the variable s into the message
# %r is used to display the string in a format that is suitable for debugging
print('The string is %r' % s)
The above code assigns the string ‘Jhon’ to the variable s. The print() function is then used to output a string to the console using string formatting with the % operator.
- The %r placeholder is used to insert a string representation of the variable s into the message.
Output: The string is 'Jhon'
In this Python tutorial, we have covered Python string formatting using the following methods:
- Using f-strings
- Using % operator
- Using the format() method
- Using string.Template class
- Using the str.format_map() method
- Using the str.maketrans() and str.translate()
- Using string concatenation
- Using the %r formatted
You may also like:
- How To Trim Whitespace from a String in Python
- String Comparison in Python
- Python Program to convert String to a List
- How to concatenate all elements of list into string in Python
- How to reverse a string in Python
- convert numpy array to list of strings in Python
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.