python strings https://www.skillvertex.com/blog Tue, 19 Mar 2024 06:51:02 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://www.skillvertex.com/blog/wp-content/uploads/2024/01/favicon.png python strings https://www.skillvertex.com/blog 32 32 Python String Formatting https://www.skillvertex.com/blog/python-string-formatting/ https://www.skillvertex.com/blog/python-string-formatting/#respond Tue, 19 Mar 2024 06:51:02 +0000 https://www.skillvertex.com/blog/?p=7587 Read more]]>

Table of Contents

The String formatting will help you to produce dynamic strings that contain variables and values. Check out this article to learn more about Python String Formatting

How to Format Strings in Python?

The format () will help you to format the selected parts of the string. However, some parts couldn’t be controlled.

Thus, to control such values, you have to add placeholders (curly brackets{} ) in the text and run the values with the format() method.

What are the different ways for String Formatting in Python?

The five different ways to operate the string formatting in Python. These methods are listed below:

  • Formatting with % Operator.
  • Formatting with format() string method.
  • Formatting with string literals, called f-strings.
  • Formatting with String Template Class
  • Formatting with center() rowPython Stringmethod.

a.How to Format String using the % Operator in Python?

This is considered the oldest method of string formatting. We use the modulo % operator. The modulo % is referred to as the string-formatting operator.

Python Format String Using the % Operator

Let us look into the example of Python Format String using the % Format.

name = "John"
age = 25
height = 5.8

# Using the % operator for string formatting
formatted_string = "My name is %s, I am %d years old, and my height is %.2f feet." % (name, age, height)

# Print the formatted string
print(formatted_string)

Output

My name is John, I am 25 years old, and my height is 5.80 feet.

How to Inject Multiple Strings Using the Modulo Operator in Python?

Let us check out the example to inject with the % operator.

# Define multiple values
name = "Alice"
age = 30
city = "Wonderland"

# Use the % operator to inject multiple strings
formatted_string = "Hello, my name is %s, I am %d years old, and I live in %s." % (name, age, city)

# Print the formatted string
print(formatted_string)

Output

Hello, my name is Alice, I am 30 years old, and I live in Wonderland.

How to Precision Handling in Python using % Operator?

The Floating Point numbers will use the format %abf. Thus, a would be considered as the minimum number of digits that is available in the string. But, it will have padded space when the whole number doesn’t have many digits.

Moreover, bf will display how many digits will be shown after the decimal point.

Example

%.2f is considered a placeholder for a floating-point number (number), and %.2f will indicate the number that should be formatted with two decimal places.

# Define a floating-point number
number = 3.141592653589793

# Use the % operator for precision handling
formatted_string = "The value of pi with 2 decimal places: %.2f" % number

# Print the formatted string
print(formatted_string)

Output

The value of pi with 2 decimal places: 3.14

What are Multiple Format Conversion Types in Python?

# Define variables with different types
name = "Alice"
age = 25
height = 5.8

# Use the % operator for multiple format conversion types
formatted_string = "Name: %s, Age: %d, Height: %.2f" % (name, age, height)

# Print the formatted string
print(formatted_string)

Output

Name: Alice, Age: 25, Height: 5.80

b.How to Format String using format() Method?

The Format () method was developed with Python 3 for monitoring the complex string formatting more smoothly.

Formatters will perform by putting in one or more replacement fields and placeholders that are defined by the pair of curly braces{} into the string and referred to as the str. format{}.

Syntax

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

Formatting with the String Pythod using the format() Method

{} is using this curly braces as the placeholder. Hence, this formatting is done through the format() method that is placed on the equal to the placeholder.

Example

In the example illustrated below, this {} is referred to as a placeholder for the variable and the values will be given as arguments to the format () method. Whereas, the {:2f} is the placeholder for the floating-point number(height) with two decimal places

# Define variables with different types
name = "Alice"
age = 25
height = 5.8

# Use the format() method for string formatting
formatted_string = "Name: {}, Age: {}, Height: {:.2f}".format(name, age, height)

# Print the formatted string
print(formatted_string)

Output

Name: Alice, Age: 25, Height: 5.80

Index-based Insertion

The code below will tell us how to perform the index-based insertion into the list in Python

# Initial list
my_list = [1, 2, 3, 5]

# Index at which to insert the new element
index_to_insert = 3

# Element to insert
new_element = 4

# Perform index-based insertion
my_list.insert(index_to_insert, new_element)

# Print the updated list
print("Updated list:", my_list)

Output

Updated list: [1, 2, 3, 4, 5]

Insert Objects by Assigning Keywords

In the example provided below, each object will be represented with keywords such as ‘name’, ‘age’, and ‘height’. So, these dictionaries will be appended to the ‘objects_list’.

# Initialize an empty list to store objects
objects_list = []

# Object 1
object1 = {'name': 'Alice', 'age': 25, 'height': 5.6}
objects_list.append(object1)

# Object 2
object2 = {'name': 'Bob', 'age': 30, 'height': 6.1}
objects_list.append(object2)

# Print the list of objects
print("List of Objects:", objects_list)

Output

List of Objects: [{'name': 'Alice', 'age': 25, 'height': 5.6}, {'name': 'Bob', 'age': 30, 'height': 6.1}]

Reuse the inserted objects

Let us look into the example below:

# Initialize an empty list to store objects
objects_list = []

# Object 1
object1 = {'name': 'Alice', 'age': 25, 'height': 5.6}
objects_list.append(object1)

# Object 2
object2 = {'name': 'Bob', 'age': 30, 'height': 6.1}
objects_list.append(object2)

# Print the original list of objects
print("Original List of Objects:", objects_list)

# Access and modify the inserted objects
objects_list[0]['age'] = 26
objects_list[1]['height'] = 6.2

# Print the modified list of objects
print("Modified List of Objects:", objects_list)

Output

Original List of Objects: [{'name': 'Alice', 'age': 25, 'height': 5.6}, {'name': 'Bob', 'age': 30, 'height': 6.1}]
Modified List of Objects: [{'name': 'Alice', 'age': 26, 'height': 5.6}, {'name': 'Bob', 'age': 30, 'height': 6.2}]

Float Precision with the format() Method

The syntax is given below

{[index]:[width][.precision][type]}

The type can be used with format codes:

‘d’ for integers
‘f’ for floating-point numbers
‘b’ for binary numbers
‘o’ for octal numbers
‘x’ for octal hexadecimal numbers
‘s’ for string
‘e’ for floating-point in an exponent format

Example

Check out the example given below for more understanding:

# Define a floating-point number
pi_value = 3.141592653589793

# Format the float with specific precision using the format() method
formatted_float = "The value of pi with 2 decimal places: {:.2f}".format(pi_value)

# Print the formatted string
print(formatted_float)

Output

The value of pi with 2 decimal places: 3.14

c. Understanding Python f-String

PEP 498 has developed a new string that has a formatting mechanism known as Literal String Interpolation. Hence, it is most commonly known as F-Strings. The concept behind the f-string in Python is to make the string Interpolation simpler.

Moreover, to create the f-string in Python, it is required to prefix the string with the letter ”f”. So, the string itself will be formatted similarly to the str. format(). F-strings will offer a proper way to embed the Python expression inside the string literals for formatting.

String Formatting with F-Strings

Check out the example given below to learn how to format the string with the F-strings.

# Define variables
name = "Alice"
age = 25
height = 5.8

# Format the string using f-string
formatted_string = f"Name: {name}, Age: {age}, Height: {height:.2f}"

# Print the formatted string
print(formatted_string)

Output

Name: Alice, Age: 25, Height: 5.80

How to do Arithmetic Operations using the F?

Let us look into the example given below:

# Define variables
a = 10
b = 5

# Perform arithmetic operations
sum_result = a + b
difference_result = a - b
product_result = a * b
division_result = a / b

# Format the string using f-string with arithmetic operations
formatted_string = f"Sum: {sum_result}, Difference: {difference_result}, Product: {product_result}, Division: {division_result:.2f}"

# Print the formatted string
print(formatted_string)

Output

Sum: 15, Difference: 5, Product: 50, Division: 2.00

How to do Lambda Expressions using F-strings

Check out the example below to learn more about the Lambda Expressions using the F-strings.

# Define a lambda function
square = lambda x: x**2
double = lambda x: x*2

# Define a variable
number = 5

# Use f-strings with lambda expressions
formatted_string = f"Square of {number} is {square(number)}, Double of {number} is {double(number)}"

# Print the formatted string
print(formatted_string)

Output

Square of 5 is 25, Double of 5 is 10

Float Precision in the f-String Method

F-string Formatting will be used to interpolate the value of the num variable into the string.

Syntax

{value:{width}.{precision}}

Example

num = 3.14159
 
print(f"The valueof pi is: {num:{1}.{5}}")

Output

The valueof pi is: 3.1416

d. Python String Template Class

In Python, there’s a tool called the Template class in the ‘string’ module. It helps us create sentences with blanks that we can fill in later.

Example

from string import Template

# Create a sentence template
template_sentence = Template("My name is $name, I am $age years old, and my height is $height feet.")

# Fill in the blanks with actual information
info = {'name': 'Alice', 'age': 25, 'height': 5.8}

# Put the information into the sentence
final_sentence = template_sentence.substitute(info)

# Show the complete sentence
print(final_sentence)

We have blank spaces represented by $name, $age, and $height. The Template class helps us replace these blanks with real information.

Output

"My name is Alice, I am 25 years old, and my height is 5.8 feet."

e. Format String Using Center () Method

The center() method is referred to as a build-in method in the Python str class and will return the new string which is centered within the string of the specified width.

Example

# Define a string
text = "Hello, Python!"

# Use the center() method to center-align the string within a width of 20 characters
centered_text = text.center(20)

# Print the centered string
print("Original String:", text)
print("Centered String:", centered_text)

Output

Original String: Hello, Python!
Centered String:   Hello, Python!  

Conclusion

In summary, Python offers multiple ways to format strings, and the choice depends on your preferences, project needs, and the version of Python you’re using. Focusing on readability ensures that your code is clear and easy to work with.

Python String Formatting- FAQs

Q1.What is string formatting in Python?

Ans. It is the process of inserting a custom string or variable in predefined text

Q2. What is %s and %d in Python?

Ans. %s – String is referred to as any object with a string representation, like numbers) %d is known as Integers. %f is called the Floating point number.

Q3.Why is R used in Python?

Ans. The ‘r’ prefix when defining a string is particularly helpful when you want to use a backslash as an actual backslash.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

]]>
https://www.skillvertex.com/blog/python-string-formatting/feed/ 0